整数数组中最大子数组的和

  设计思想:一个数组中查找最大子数组,就是把从头开始进行累加,如果累加和大于0就需要接着加下一项,如果小于0则重新进行累加。累加完毕之后就需要对循环数组进行累加。

  加上一个正数会使原有的数变大,而加上一个负数会使原有的数变小,具体做法是依次遍历数组中的每一个数,并记下截至当前位置的最大和及当前和,如果当前和小于0就应该舍弃之,而从新的位置开始计算。另外对于一个既包含正数又包含负数的整型数组,其最大的子数组的和至少应该大于0。

  出现问题:没有弄清楚最大子数组的计算方法。

  程序源代码:

 1 package 最大子数组;
 2 
 3 public class judge {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7 
 8         int arrary[]={3,-2,3,-4,5,6,7,8};
 9         System.out.println(findMaxArray(arrary));
10     }
11 
12     
13     public static int findMaxArray(int[] array){
14         if (array == null || array.length == 0) {
15             return Integer.MIN_VALUE;
16         }
17         int maxSum = Integer.MIN_VALUE;
18         int currentSum = 0;
19         int j=0;
20         for (int i = 0; i < j+array.length; i++) {
21             if (currentSum < 0) {
22                 currentSum = array[i%array.length];
23                 j=i;
24             }else {
25                 currentSum += array[i%array.length];
26             }
27             maxSum = Math.max(maxSum, currentSum);
28         }
29         return maxSum;
30     }
31 }

  运行结果截图:

 

  总结:整个程序并不复杂,但是中间的计算方法才是困难的,这说明我的编程时间还是不够多,我还需要在多多努力。

posted @ 2017-03-31 19:04  风飘万点江满月  阅读(189)  评论(0编辑  收藏  举报