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
.
典型的DP问题,递推条件还是想了有点长时间,代码如下所示:
1 class Solution { 2 public: 3 int maxSubArray(vector<int>& nums) { 4 vector<int> ans; 5 int sz = nums.size(); 6 if(!sz) return 0; 7 ans.resize(sz); 8 ans[0] = nums[0]; 9 int maxSum = nums[0]; 10 for(int i = 1; i < sz; ++i){ 11 ans[i] = max(nums[i], ans[i - 1] + nums[i]); //这里的条件应该注意 12 maxSum = max(ans[i], maxSum); 13 } 14 return maxSum; 15 } 16 };