LeetCode 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
.
区间最大和问题,只需要用一个变量维护上一个区间的和,如果小于0
的话就舍弃,大于0
的话就加上。
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int ans = INT_MIN, res = 0;
for(size_t i = 0; i < nums.size(); ++ i)
{
if(res < 0)
res = 0;
res += nums[i];
ans = max(ans, res);
}
return ans;
}
};