Question:

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Thinking:

  • Method:DP
    1. 记录下每个点的值,存在二维数组中。这种方法O(On^2),但是占空间,无法AC
class Solution {
    public int maxSubArray(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        int len = nums.length;
        int[][] dp = new int[len][len];
        int result = Integer.MIN_VALUE;
        for(int i = 0; i < len; i++){
            dp[i][i] = nums[i];
            result = Math.max(result, nums[i]);
        }
        for(int i = 0; i < len - 1; i++){
            for(int j = i + 1; j < len; j++){
                dp[i][j] = dp[i][j - 1] + nums[j];
                result = Math.max(result, dp[i][j]);
            }
        }
        return result;
    }
}
  • Method 2: 1.第二种方法是O(n),仍然是通过DP。
    • 缓存两个值,最大值res,以及以某个点为开头的最大值cur。
    • 什么时候更新cur,当某个点的值大于所缓存的值的时候[4, -6, 3],此时前两个的缓存值为-2,而第三个值本身为3,所以加上前两个值本身就是浪费,此时我们就以3为开头进行继续运算。
class Solution {
    public int maxSubArray(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        int len = nums.length;
        int curr = nums[0];
        int res = nums[0];
        for(int i = 1; i < len; i++){
            curr = Math.max(nums[i], nums[i] + curr);
            res = Math.max(res, curr);
        }
        return res;
    }
}

二刷

二刷的时候还借鉴了一刷的结果。

class Solution {
    public int maxSubArray(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        int cur = nums[0], max = nums[0];
        for(int i = 1; i < nums.length; i++){
            cur = Math.max(nums[i], cur + nums[i]);
            max = Math.max(cur, max);
        }
        return max;
    }
}