动态规划之最长子序列之和
2020-06-20 本文已影响0人
wyh2107
剑指 Offer 42 leetcode: https://leetcode-cn.com/problems/lian-xu-zi-shu-zu-de-zui-da-he-lcof/
/**
* 借助数组
* @param nums
* @return
*/
public static int maxLength(int[] nums) {
if (nums == null || nums.length < 1) {
return 0;
}
int[] dp = new int[nums.length];
dp[0] = nums[0];
int max = dp[0];
for (int i = 1; i < dp.length; i++) {
System.out.println("i = " + i);
if (dp[i - 1] <= 0) {
dp[i] = nums[i];
} else {
dp[i] = dp[i - 1] + nums[i];
}
max = Math.max(max, dp[i]);
}
return max;
}
/**
* 其实只需要用到前一个值,滚动数组
* @param nums
* @return
*/
public static int maxLength01(int[] nums) {
if (nums == null || nums.length < 1) {
return 0;
}
int i = 1;
int prev = nums[0];
int max = prev;
while ( i < nums.length ) {
if (prev <= 0) {
prev = nums[i];
} else {
prev = prev + nums[i];
}
max= Math.max(prev, max);
i ++;
}
return max;
}