53. 最大子序和(dp)
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 n = nums.size(); vector<int> dp = vector<int>(n,0); int res = nums[0]; dp[0] = nums[0]; for(int i = 1; i < n;i++) { //. 要么清0 从当前值开始,要么加上当前值 dp[i] = max(nums[i],dp[i-1]+nums[i]); res = max(res, dp[i]); } return res; } };
递归方程;
dp[i] = dp[i-1]+nums[i] ,dp[i-1]>0
dp[i] = nums[i] ,else
1 class Solution { 2 public int maxSubArray(int[] nums) { 3 int dp[] = new int[nums.length+1]; 4 int max = nums[0]; 5 dp[0] = nums[0]; 6 for(int i =1;i<nums.length;i++){ 7 if(dp[i-1]<=0) 8 dp[i] = nums[i]; 9 else 10 dp[i] = dp[i-1]+nums[i]; 11 max = Math.max(dp[i],max); 12 } 13 return max; 14 } 15 }