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.
Solution
这道题是求最大连续子串的和。我们可以采用动态规划的方法来解决。
dp[i] 为以A[i]结尾的最大连续子串的和。
如果dp[i-1] < 0, 那么以A[i]结尾的话,无论A[i]为正还是负,加上一个负数,总会小于它本身,所以dp[i] = A[i];
如果dp[i-1] > 0, 那么dp[i] = A[i]+dp[i-1];
在这个过程中需要记录dp数组的最大值。
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
int dp[n];
dp[0] = nums[0];
int m = dp[0];
for (int i = 1; i < n; i++) {
if (dp[i-1] > 0) {
dp[i] = nums[i]+dp[i-1];
} else {
dp[i] = nums[i];
}
m = max(dp[i], m);
}
return m;
}
};