Find the contiguous subarray within an array (containing at least one
number) which has the largest sum.

For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous
subarray [4,−1,2,1] has the largest sum = 6.

动态规划

思路

state: dp[i] 表示前i步的最大值
function: 如果前一步的最大值dp[i-1] < 0 那么第i步最大值是就是第i步本身, 如果dp[i - 1] >0 则为和
用一个max记录最大值
intialize: 起点dp[0] = sum[0]
answer: max

复杂度

时间O(n) 空间O(n)

代码

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

复杂度

时间O(n) 空间O(1)

代码

public int maxSubArray(int[] nums) {
    if (nums == null || nums.length == 0) {
        return 0;
    }
    int dp =  nums[0];
    int max = dp;
    for (int i = 1; i < nums.length; i++) {
        dp = dp > 0 ? dp + nums[i] : nums[i];
        max = Math.max(dp, max);
    }
    return max;
}

lpy1990
26 声望10 粉丝