爱程序网

[LeetCode] 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.

 

     这道题呢在题目里的提示tag里就说了要用dynamic programming来做。所以我们先明确一下dynamic programming的定义:

     We should ignore the sum of the previous n-1 elements if nth element is greater than the sum.

     所以根据定义来说,这道题找subarray的话,如果第N个数大于【它本身和前面N-1个数的总和】的话,我们就可以直接无视前面的N-1个数了。

     所以我们可以用两个Math.max来计算,一个用来检查是否需要无视前面n-1个数,一边则把新得出来的算术结果与之前已知的最大结果进行比较。

     需要注意的是,因为一般初始max值都是设的是第一个数的值,所以用dynamic programming的时候,loop时我们可以直接从i=1开始。

     代码如下:

public class Solution {
    public int maxSubArray(int[] nums) {
        //dynamic programming:
        //We should ignore the sum of the previous n-1 elements if nth element is greater than the sum."
        
        int[] result=new int[nums.length];
        result[0]=nums[0];
        int max=nums[0];
        for(int i=1;i<nums.length;i++){
            result[i]=Math.max(nums[i],result[i-1]+nums[i]);
            max=Math.max(max,result[i]);
        }
        return max;
    }
}

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助