[leetcode] Maximum Subarray 解题报告

题目链接:https://leetcode.com/problems/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.

思路:一道比较经典的题目,可以使用贪心或者动归来做。状态转移方程为:

dp[i] = max(dp[i-1] + A[i-1], A[i-1])

即如果之前的序列和小于0,则加上任何数都会小于这个数,所以序列从当前数重新开始算。

时间复杂度为O(n), 空间复杂度为O(1).

代码如下:

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        if(nums.size() == 0)
            return 0;
        int maxSum = INT_MIN, curSum = 0;
        for(int i = 0; i < nums.size(); i++)
        {
            curSum = max(curSum + nums[i], nums[i]);
            maxSum = max(maxSum, curSum);
        }
        return maxSum;
    }
};


你可能感兴趣的:(LeetCode,动态规划,greedy)