53. Maximum Subarray

来源:互联网 发布:linux内核编译详解 编辑:程序博客网 时间:2024/06/05 03:39

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.

click to show more practice.

AC代码(Java版):

public int maxSubArray(int[] A) {    int max = A[0], dp = A[0];    for (int i = 1; i < A.length; i++) {                    dp = Math.max(dp + A[i] ,A[i]);        max = Math.max(max, dp);    }    return max;}

摘自Discuss:

Just do DP, use curMax to calculate the maximum sum ending at nums[i], so the recurisve equation is
curMax at i+1 = max(0, curMax) + nums[i+1]

代码:

class Solution {public:    int maxSubArray(vector<int>& nums) {        int curMax = 0, res = INT_MIN, i;        for(auto x:nums)        {            curMax = curMax>0? (curMax + x):x ;            if(curMax > res ) res = curMax;        }        return res;    }};


其实两段代码思路一模一样,但是第二个读上去舒服一点。。。

原创粉丝点击