Maximum subarray

。題目假設

給一個數組,找出連續和最大的子數組

。重要問題

。直覺

動態規劃

。解決方法可行性

。解決方案

。資料結構

。複雜度

。遇到的困難點、想錯的地方

思考方式:

求連續最大和,那麼如果前面的連續之和已經是負數,我就可以捨棄直接不用,

因為一個數加上一個負數一定不會比較大

我們還需要一個當前之和,當前之和就是連續之和

public int maxSubArray(int[] nums) {
    if (nums == null || nums.length == 0) {
        return Integer.MIN_VALUE;
    }

    int max = nums[0];
    int cur = nums[0];
    for (int i=1; i<nums.length; i++)
    {
        cur = cur < 0 ? nums[i] : cur+nums[i];
        max = Math.max(max, cur);
    }
    return max;
}

results matching ""

    No results matching ""