[leetcode-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.
思路:
需要一个变量temp来保存子序列的和,如果temp<0,说明再往下加新元素的时候,新的子序列的和一定会比新元素要小。有点儿绕,举个例子,比如此时temp == -1,下一个元素为5,如果保留temp为-1,那么新的序列和为-1+5 =4,比5还小。所以这种情况下,需temp从0开始,即将temp更新为0。
还需要一个变量来保存最大的子序列的和即最大的temp值。
这样仅需一次扫描即可,时间复杂度为O(n).
int maxSubArray(vector<int>& nums) { if (nums.empty())return 0; int temp = 0,result = nums[0]; for (int i = 0; i < nums.size();i++) { temp += nums[i]; result = max(result,temp); temp = max(temp,0); } return result; }
参考:
https://discuss.leetcode.com/topic/3400/simplest-and-fastest-o-n-c-solution