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
.
Subscribe to see which companies asked this question.
题目分析:
按题目要求需要求出具有最大和的子集。可以知道,此子集必定在其左右全为正数,然而,我在此题中并没有很明显的利用这个性质,-- _ --.
一开始我也没有什么好的思路,我想一位位地循环,想来当遇到nums[i]时就判断是将其加入子数组还是单独作为一个新的开头。若是,其加入子数组起的作用没有自己开头大(即子数组和没有nums[i]大),就自己开头,否则加入子数组。但是,我发现这并不能解决问题,因为用这种方法,每当遇到负数都会被加入子数组,这显然不对。所以,我就设置两个great和sgreat,后者用来保存未加入负数时地最大和,前者则是加了负数的结果,取其最大值放入sgreat,避免出现这种低级错误。最后返回的sgreat,就是题目所要求的值啦。
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int great=nums[0];
int sgreat=great;
int n=nums.size();
for(int i=1;i<n;i++)
{
if(nums[i]>=nums[i]+great) great=nums[i];
else great+=nums[i];
sgreat=max(sgreat,great);
}
return sgreat;
}
};