LeetCode/solutions/53. Maximum Subarray.md

26 lines
873 B
Markdown
Raw Normal View History

2018-09-01 11:45:24 +00:00
# [53. Maximum Subarray](https://leetcode.com/problems/maximum-subarray/description/)
# 思路
2020-02-09 11:32:49 +00:00
就是一个简单的动态规划。从前往后遍历一遍用currsum记录以当前位置为结尾的最大子序列和。可见currsum要么等于nums[i]本身要么等于nums[i]加上上一个currsum即更新准则为
* 如果currsum大于0那么`currsum += nums[i]`
* 否则,则`currsum = nums[i]`。
时间复杂度O(n)空间复杂度O(1)
2018-09-01 11:45:24 +00:00
# C++
2019-09-13 15:08:41 +00:00
``` C++
2018-09-01 11:45:24 +00:00
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int maxsum = nums[0]; // at least one number
int currsum = nums[0];
for(int i = 1; i < nums.size(); i++){
if(currsum > 0) currsum += nums[i];
else currsum = nums[i];
if(currsum > maxsum) maxsum = currsum;
}
return maxsum;
}
};
```