您的位置:首页 > 其它

53. Maximum Subarray

2016-03-28 10:52 197 查看
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
.

看《剑指offer》看到这道题,过来刷一下···

class Solution {
public:
int maxSubArray(vector<int>& nums) {
int cursum=0;
int greatestsum=0x80000000;     //可以表示的最大的负数
for(int i=0;i<nums.size();i++){
if(cursum<=0)              //如果cursum为负,如果算上cursum会小于不算cursum开始的子数组的和,因此不需要前面的子数组,cursum扔掉
cursum=nums[i];
else cursum+=nums[i];
if(cursum>greatestsum)
greatestsum=cursum;
}
return greatestsum;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: