题目描述:
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
.
使用动态规划,计算以数组中的每一个元素为最后一个元素的子数组的和的最大值,然后取最大的值即可。
遍历数组nums,用一个变量cur_sum保存以当前元素为最后一个元素的子数组的最大和(假设当前遍历到的元素为i):
(1)如果cur_sum<=0,更新cur_sum=nums[i]
(2)如果cur_sum>0,更新cur_sum=cur_sum+nums[i]
AC代码如下:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if (nums.size() == 0) return 0;
int cur_sum = nums[0];
int ans = cur_sum;
int n = nums.size();
for (int i = 1; i < n; ++i){
if (cur_sum <= 0){
cur_sum = nums[i];
}
else{
cur_sum += nums[i];
}
ans = max(ans, cur_sum);
}
return ans;
}
};