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 n=nums.size();
int res=nums[0];
int k=nums[0],i;
for(i=1;i<n;i++)
{
//前面的数值不能是负的
k=(k>0)?(k+nums[i]):nums[i];
res=max(k,res);
}
return res;
}
};