leetcode 53. Maximum Subarray

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.

分析:

给出一个数组,求数组中连续的几个数相加的最大值,

这种题需要考察我们找到最优解的抽象建模公式。

对于给出的数组中的i元素,如果它加到上一组可以使上一组的值比自己本身大,它就应该加到前面的子集中,

如果它本身值足够大,比前面几个元素相加的值要大,它可以自己作为一个子集的起始点继续向下寻找。

这道题简单的最优解公式为sum[i] = Math.max(sum[i - 1] + nums[i], nums[i]);

此外,我们需要用一个max变量动态的纪录这些子集的相加最大值,最后作为结果返回。

public class Solution {
    public int maxSubArray(int[] nums) {
        int[] sum = new int[nums.length];
        int max = nums[0];
        sum[0] = nums[0];
        
        for (int i = 1; i < nums.length; i++){
            sum[i] = Math.max(sum[i - 1] + nums[i], nums[i]);
            max = Math.max(max,sum[i]);
        }
        return max;
    }
}
原文地址:https://www.cnblogs.com/iwangzheng/p/5728617.html