LeetCode:Maximum Subarray

Maximum Subarray

Total Accepted: 91379  Total Submissions: 256225  Difficulty: Medium

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.


Hide Tags
  Divide and Conquer Array Dynamic Programming














思路:

动态规划

由[-2, 1,-3, 4,-1, 2, 1,-5, 4]可得其dp数组,

[-2, 1,-2, 4, 3, 5, 6, 1, 5]。

即其状态转移过程为:

if (dp[i-1]>0) dp[i] = nums[i] + dp[i-1];
else dp[i] = nums[i] + 0;

即如果dp为负则重选序列。

code:

动规:

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int len = nums.size();
        if(0==len) return 0;
        vector<int> dp(len);
        dp[0]=nums[0];
        int res=nums[0];
        for(int i=1;i<len;i++) {
            dp[i] = nums[i] + (dp[i-1] > 0 ? dp[i-1]:0);
            res = dp[i] > res? dp[i] :res;
        }
        return res;
    }
};

动划 + 滚动数组(数):

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int len = nums.size();
        if(0==len) return 0;
        int dp = nums[0];
        int res = dp;
        for(int i = 1; i<len; i++) {
            dp = nums[i] + (dp > 0 ? dp : 0);
            res = dp > res ? dp : res;
        }
        return res;
    }
};


你可能感兴趣的:(LeetCode,maximum,53,Subarray)