首页 > 学院 > 开发设计 > 正文

[LeetCode] Maximum Subarray

2019-11-15 01:08:02
字体:
来源:转载
供稿:网友
[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;    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表