连续子数组的最大和

题目:输入一个整型数组,数组里有正数也有负数。数组中一个或连续的多个整数组成一个子数组。求所有字数组的和的最大值。要求时间复杂度为O(n).

public class Main {
    public static int getMaxSum(int[] array) throws Exception{
        
        if (array == null && array.length == 0) {
            throw new Exception() ;
        }
        
        int maxSum = array[0];
        int tempSum = maxSum;
        for (int i = 1; i < array.length; i++) {
            if (tempSum < 0) {
                tempSum = array[i];
            } else {
                tempSum += array[i];
            }
            
            if (tempSum >= maxSum) {
                maxSum = tempSum;
            }
        }
        return maxSum;
    }
    
    public static void main(String[] args) {
        int[] array = {-1, -2, -3, -10, -4, -5, -2, -5};
        try {
            System.out.println(getMaxSum(array));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 另外一种方法:

 1 /**
 2      * 
 3      * @param a 数组序列
 4      * @param seqStart 子序列的开始位置
 5      * @param seqEnd   子序列的结束位置
 6      * @return 连续子序列最大和
 7      */
 8     public static int maximumSubsequenceSum(int[] a, int seqStart, int seqEnd){
 9         int maxSum = 0;
10         int thisSum = 0;
11         
12         for (int i = 0, j = 0; j < a.length; j++) {
13             thisSum += a[j];
14             
15             if (thisSum > maxSum) {
16                 maxSum = thisSum;
17                 seqStart = i;
18                 seqEnd = j;
19             } else if (thisSum < 0) {/* 遇到一个序列的和为负数  重新开始计算 */
20                 i = j + 1;
21                 thisSum = 0;
22             }
23         }
24         return maxSum;
25     }

 

posted @ 2014-09-11 09:14  soul390  阅读(130)  评论(0)    收藏  举报