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
.
DP问题,找到递推公式是关键。
local = max(local+nums[i],nums[i])
global = max(global,local)
这就是递推公式。
1 class Solution { 2 public: 3 int maxSubArray(vector<int>& nums) { 4 if(nums.size()==0) return 0; 5 int global = nums[0],local=nums[0]; 6 for(int i=1;i<nums.size();i++) 7 { 8 local = max(local+nums[i],nums[i]); 9 global = max(global,local); 10 } 11 return global; 12 } 13 };