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
.
这道题目是Momenta面试题的原题,当时磕磕绊绊没有AC,今天秒了。
这道题的本质上其实是一个动态规划题,下面推导状态转移:
设f(i)为第i个数之前(包括第i个数)最大子数组的和,我们要求的即为f(n),
设g(i)为第i个之前(包括第i个数)且包含第i个数的最大子数组的和。
g(i)和f(i)的差别在于g(i)的最大和子数组一定是要包含第i个数。
下面分别写出f(i), g(i)的递推公式。
g(i) = max (0, g(i-1) + v(i))
f(i) = max (f(i-1), g(i))
所以我们得到了递推公式,求出f(n)即可。
在写代码的过程中,我们注意到g(i)之前的项不要要保存,所以可以直接常数空间解决战斗,AC代码如下:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int ans = nums[0];
int ans_with_this = 0;
for (int i = 0; i < nums.size(); i++){
if (ans_with_this + nums[i] > 0){
// We add num[i] to the ans_with_this
ans_with_this += nums[i];
ans = max(ans, ans_with_this);
} else {
ans_with_this = 0;
}
ans = max(ans, nums[i]);
}
return ans;
}
};