题目链接: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; } };