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.
代码如下:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int const n = nums.size();
int dp[n];
int max_ = nums[0];
dp[0] = nums[0];
for (int i = 1; i < nums.size(); i++) {
dp[i] = dp[i - 1] > 0 ? dp[i - 1] + nums[i] : nums[i];
max_ = max(max_, dp[i]);
}
return max_;
}
};
解题思路:
- 这是一道典型的动态规划题,为了求整个数组的最大子序列之和,可以先求较小数组的最大子序列之和,可以从左向右计算也可以从右向左计算,效果是一样的;
- 用数组 dp 来记录当前下标之前的最大子序列之和,若要算加上当前数字的较大子序列之和的最大值,就要判断dp[i - 1] 是否大于0,若小于零则那就没有必要加上它,因为这只会拖累子序列的最大和,如果是正数就加上它。
- 反复递归这个过程,用max_来记录此过程中出现的最大值。