Java 实现 数组最大子数组和(可选删除一个元素)
思路:使用动态规划,分别计算不删和删一个数的情况下的最大子数组和。最后比较两种情况下的最大值即可。
具体实现:
class Solution {
public int maximumSum(int[] arr) {
int n = arr.length;
int[] dp1 = new int[n]; // 不删的情况下的最大子数组和
int[] dp2 = new int[n]; // 删一个数的情况下的最大子数组和
dp1[0] = arr[0];
dp2[0] = Integer.MIN_VALUE;
int res = arr[0];
for (int i = 1; i < n; i++) {
dp1[i] = Math.max(dp1[i-1] + arr[i], arr[i]); // 不删
dp2[i] = Math.max(dp2[i-1] + arr[i], dp1[i-1]); // 删一个数
res = Math.max(res, Math.max(dp1[i], dp2[i]));
}
return res;
}
}
原文地址: https://www.cveoy.top/t/topic/opNC 著作权归作者所有。请勿转载和采集!