public class Knapsack {
public static int maxValue(int[] weights, int[] values, int W) {
int n = weights.length;
int[][] dp = new int[n + 1][W + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= W; j++) {
if (weights[i - 1] <= j) {
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weights[i - 1]] + values[i - 1]);
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[n][W];
}
public static void main(String[] args) {
int[] weights1 = {2, 3, 4};
int[] values1 = {3, 4, 5};
int W1 = 5;
int maxValue1 = Knapsack.maxValue(weights1, values1, W1);
System.out.println("测试用例1:Max value: " + maxValue1);
int[] weights2 = {2, 3, 4, 5};
int[] values2 = {3, 4, 5, 6};
int W2 = 7;
int maxValue2 = Knapsack.maxValue(weights2, values2, W2);
System.out.println("测试用例2:Max value: " + maxValue2);
int[] weights3 = {2, 3, 4, 5, 6};
int[] values3 = {3, 4, 5, 6, 7};
int W3 = 10;
int maxValue3 = Knapsack.maxValue(weights3, values3, W3);
System.out.println("测试用例3:Max value: " + maxValue3);
int[] weights4 = {2, 3, 4, 5, 6, 7};
int[] values4 = {3, 4, 5, 6, 7, 8};
int W4 = 15;
int maxValue4 = Knapsack.maxValue(weights4, values4, W4);
System.out.println("测试用例4:Max value: " + maxValue4);
}
}