zoukankan      html  css  js  c++  java
  • Java 数组中寻找最大子数组

     程序设计思想:
    依次将数组划分开,先判断一个元素的单个数组大小,接下来两个,依次上升,最后将所得结果进行比较赋值,输出最大结果。

    1
    package ketangTest; 2 //张生辉,康治家 2017.3.20 3 public class Test { 4 public static void main(String args[]){ 5 int b[]={-7,9,-2,84}; 6 int a[]={-7,9,-2,84,-7,9,-2,84}; 7 int max,max2,max3,max4; 8 max=a[0]; 9 int Max=max;//Max值每次都与最大值判断,之后替代 10 for(int i=0;i<a.length;i++) 11 { 12 if(a[i]>max) 13 { 14 max=a[i]; 15 } 16 max2=max; 17 if(i<a.length-1)//处理越界问题,判断越界跳过即可 18 { 19 if(a[i]+a[i+1]>max2) 20 { 21 max2=a[i]+a[i+1]; 22 } 23 } 24 max3=max2; 25 if(max3>Max) 26 { 27 Max=max3; 28 } 29 if(i<a.length-2) 30 { 31 if(a[i]+a[i+1]+a[i+2]>max3) 32 { 33 max3=a[i]+a[i+1]+a[i+2]; 34 } 35 } 36 max4=max3; 37 if(max4>Max) 38 { 39 Max=max4; 40 } 41 if(i<a.length-3) 42 { 43 if(a[i]+a[i+1]+a[i+2]+a[i+3]>max4) 44 { 45 max4=a[i]+a[i+1]+a[i+2]+a[i+3]; 46 } 47 } 48 if(max4>Max) 49 { 50 Max=max4; 51 } 52 53 } 54 System.out.println(Max); 55 } 56 57 }
    程序运行结果截图:
    程序编译错误结果分析:
    因为在判断数组时需要利用一个For循环,最后导致在判断一个元素的For循环下,判断两个及以上的时候会出现越界,于是加入判断条件来限制就可以解决这问题。
  • 相关阅读:
    python参考手册--第3章类型和对象
    python参考手册--第2章词汇和语法约定
    Kafka 分布式环境搭建
    常用sql语句
    ValueError: Attempted relative import in non-package
    mysql查询缓存
    secureCRT配色
    mysql deadlock处理
    How to Cope with Deadlocks
    ajax同步
  • 原文地址:https://www.cnblogs.com/shenghuizhang/p/6646914.html
Copyright © 2011-2022 走看看