Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
很经典的题目了,记得初始化为最小值。
本质是一个动态规划,f[i]=max(f[i-1],0)+a[i]
,然后数组可以简化为一个变量。
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sz=nums.size();
int res=INT_MIN,cur=0;
for(int i=0;i<sz;i++){
cur+=nums[i];
if(cur>res){
res=cur;
}
if(cur<0)cur=0;
}
return res;
}
};