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的思维,感觉,嗯。。得写写dp锻炼思维才行,要克服一下看到dp就不会写的心态
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if (nums.size() == 0) return 0;
int ans = nums[0];
int sum = 0;
for (int i = 0; i < nums.size(); ++i) {
sum += nums[i];
ans = max(ans, sum);
sum = max(sum, 0);
}
return ans;
}
};