53. Maximum Subarray (最大子数列)
题目链接
https://leetcode.com/problems/maximum-subarray/description/
题目描述
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
.
题目分析
通过分析我们可以发现:
对于某个数字,如果它前面的一个数列的和小于0,那就没有再连续起来的必要了,一个数字加上一个负数比自己还小,这样还不如从自己重新开始。于是我们得到动态规划的状态转移方程:
设sums[i]
记录的是以第i
个数字结束的数列的和的最大值
sums[i] = nums[i] + (sums[i - 1] >= 0 ? sums[i - 1] : 0)
方法:动态规划
算法描述
初始化sums[0] = nums[0], max = nums[0]
从i = 1
开始到i = nums.size() - 1
sums[i] = nums[i] + (sums[i - 1] >= 0 ? sums[i - 1] : 0)
当sums[i]
大于max时,max
置为sums[i]
参考代码
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int max = nums[0];
vector<int> sums;
sums.resize(nums.size());
sums[0] = nums[0];
for (int i = 1; i < nums.size(); i++) {
sums[i] = nums[i] + (sums[i - 1] > 0 ? sums[i - 1] : 0);
max = sums[i] > max ? sums[i] : max;
}
return max;
}
};