53. Maximum Subarray
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; } };