天天看點

【Leetcode 53】最大子序和

題目描述
【Leetcode 53】最大子序和

方法一:采用貪心法,判斷每次和是否大于0

【Leetcode 53】最大子序和
class Solution {
    public int maxSubArray(int[] nums) {
        int ans = nums[0];
        int sum = 0;
        for(int num: nums) {
            if(sum > 0) {
                sum += num;
            } else {
                sum = num;
            }
            ans = Math.max(ans, sum);
        }
        return ans;
    }
}      

方法一的變種,采用動态規劃

【Leetcode 53】最大子序和
class Solution {
    public int maxSubArray(int[] nums) {
        int pre = 0, maxAns = nums[0];
        for (int x : nums) {
            pre = Math.max(pre + x, x);
            maxAns = Math.max(maxAns, pre);
        }
        return maxAns;
    }
}      

方法二:分治法

​​https://leetcode-cn.com/problems/maximum-subarray/solution/zui-da-zi-xu-he-by-leetcode-solution/​​