連續子數組的最大和

題目描述

{6, -3, -2, 7, -15, 1, 2, 2},連續子數組的最大和爲 8(從第 0 個開始,到第 3 個爲止)。java

 

思路:數組

累加的子數組和,若是 > 0 ,繼續累加;spa

                            若是 < 0 ,刪除原來的累加和,從新開始。code

public class Solution {
     public int FindGreatestSumOfSubArray(int[] array) {
         if (array.length==0 || array==null) {
             return 0;
         }
         int curSum=0;
         int greatestSum=0x80000000;
         for (int i = 0; i < array.length; i++) {
             if (curSum<=0) {
                 curSum=array[i]; //記錄當前最大值
             }else {
                 curSum+=array[i]; //當array[i]爲正數時,加上以前的最大值並更新最大值。
             }
             if (curSum>greatestSum) {
                 greatestSum=curSum; 
             }
         }
         return greatestSum;
     }
 }
public int FindGreatestSumOfSubArray(int[] nums) {
    if (nums == null || nums.length == 0)
        return 0;
    int greatestSum = Integer.MIN_VALUE;
    int sum = 0;
    for (int val : nums) {
        sum = sum <= 0 ? val : sum + val;
        greatestSum = Math.max(greatestSum, sum);
    }
    return greatestSum;
}

須要注意的是:加強 for 的一些概念。blog

Integer.MIN_VALUE—— 它表明int所能表示的最小值 0x80000000io

greatestSum 本來是最小的負數,當 Sum > greatestSum ,時,把最大值給他。class

相關文章
相關標籤/搜索