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
.
只要知道 除非全负,任何的负的子序列不可能是最优子序列的前缀 就可以了。
我的代码:
class Solution { public: int maxSubArray(vector<int>& nums) { int max = nums[0], now = 0; for (int i = 0; i < nums.size(); i++) { now += nums[i]; if (now >= max) max = now; if (now < 0) now = 0; } return max; } };