Ideas:
And the longest increasing subsequence and longest palindromic sequence classic example similar, they are dynamic programming
State transition equation:
dp[i] represents the largest subsequence sum before the current number
1) If dp[i-1] is a positive number, just add nums[i] directly, dp[i]=dp[i-1]+nums[i]
2) If dp[i-1] is a negative number, then dp[i] only takes nums[i], which is equivalent to reselecting a new subsequence
最终dp[i]=Math.max(dp[i-1]+nums[i],nums[i])
Code 1:
class Solution {
public int maxSubArray(int[] nums) {
int n=nums.length;
int[] dp=new int[n+1];
dp[0]=nums[0];
for(int i=1;i<n;i++){
dp[i]=Math.max(nums[i],dp[i-1]+nums[i]);
}
int res=dp[0];
for(int i=1;i<n;i++){
res=Math.max(res,dp[i]);
}
return res;
}
}
break down:
1) This is the second type of dp, the current value depends on all the previously calculated values
Belong to Linear Programming
2) Two cycles are used, which can be combined into one cycle
int res=dp[0];
for(int i=1;i<n;i++){
dp[i]=Math.max(nums[i],nums[i]+dp[i-1]);
res=Math.max(res,dp[i]);
}
3) The last state cannot be directly returned here (dp[n-1]).
Output should be all the dp[0]
, , dp[1]
......,dp[n - 1]
read through, whichever is greater
The same situation also applies to "Leguo" question 300: the longest ascending subsequence.