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.

动态规划

设 f[n] 为以nums[n]为最后一个数字的最大子序列和
f[n-1] > 0 f[n] = nums[n] + f[n-1]
f[n-1] < 0 f[n] = nums[n]

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

你可能感兴趣的:(53. Maximum Subarray)