【发布时间】:2021-01-05 16:18:29
【问题描述】:
给定一个整数数组,找出小于或等于给定阈值的子序列的最大和。
限制:
数组的最大大小为 10^5
数组中元素为 10^9 时的最大大小
阈值范围为 1 到 10^9
例如
输入:
1 2 4 5
10
输出:
10
在上面的例子中,数组是[1,2,4,5],阈值是10。最大和子序列是10,由(1,4,5)组成
import java.util.Arrays;
public class MaxSumSubsequenceWithThreshold {
class Solution {
int[] A;
int threshold;
Integer[][] dp;
Solution(int[] A, int threshold) {
this.A = A; this.threshold = threshold;
dp = new Integer[A.length][threshold + 1];
}
int sum(int pos, int threshold) {
if (threshold <= 0) return 0;
if (threshold - A[pos] < 0) return dp[pos][threshold] = Integer.MIN_VALUE;
if (dp[pos][threshold] != null) return dp[pos][threshold];
int sum = 0;
int max = Integer.MIN_VALUE;
for (int i = pos + 1; i < A.length; i++) {
sum = sum(i, threshold - A[pos]);
max = Math.max(max, sum);
}
return dp[pos][threshold] = max == Integer.MIN_VALUE ? A[pos] : max + A[pos];
}
int solve() {
Arrays.sort(A);
int max = Integer.MIN_VALUE;
for (int i = 0; i < A.length; i++) {
dp[i][threshold] = sum(i, threshold);
max = Math.max(max, dp[i][threshold]);
}
return max;
}
}
public static void main(String[] args) {
int[] A = InputUtils.nextIntLine();
int threshold = InputUtils.nextInt();
System.out.println(
new MaxSumSubsequenceWithThreshold().new Solution(A, threshold).solve()
);
}
}
在验证此解决方案是否正确时需要帮助。
有更好的解决方案吗?
【问题讨论】:
-
为了更好的解决方案,不要使用递归。
-
阈值是否有限制,例如
1 <= threshold <= 100之类的?可以有多少个值? -
在描述中添加阈值范围。
标签: java arrays algorithm recursion dynamic-programming