|
| 1 | +package dp; |
| 2 | + |
| 3 | +/** |
| 4 | + * Given weights and values of n items, put these items in a knapsack of capacity W to get the |
| 5 | + * maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and |
| 6 | + * wt[0..n-1] which represent values and weights associated with n items respectively. Also given |
| 7 | + * an integer W which represents knapsack capacity, find out the maximum value subset of val[] |
| 8 | + * such that sum of the weights of this subset is smaller than or equal to W. You cannot break an |
| 9 | + * item, either pick the complete item, or don’t pick it (0-1 property) |
| 10 | + */ |
| 11 | +public class Knapsack { |
| 12 | + |
| 13 | + public static void main(String[] args) { |
| 14 | + rknapsack(5, new int[]{60, 100, 120}, new int[]{1, 2, 3}); |
| 15 | + rknapsack(10, new int[]{60, 100, 120, 130, 140}, new int[]{1, 2, 3, 4, 5}); |
| 16 | + rknapsack(10, new int[]{0, 60, 100, 120, 130, 140}, new int[]{0, 1, 2, 3, 4, 5}); |
| 17 | + dp(5, new int[]{60, 100, 120}, new int[]{1, 2, 3}); |
| 18 | + dp(10, new int[]{60, 100, 120, 130, 140}, new int[]{1, 2, 3, 4, 5}); |
| 19 | + dp(10, new int[]{0, 60, 100, 120, 130, 140}, new int[]{0, 1, 2, 3, 4, 5}); |
| 20 | + } |
| 21 | + |
| 22 | + static void dp(int W, int[] values, int[] weights) { |
| 23 | + int dp[][] = new int[values.length + 1][W + 1]; |
| 24 | + |
| 25 | + for (int i = 1; i <= values.length; i++) { |
| 26 | + for (int j = 1; j <= W; j++) { |
| 27 | + dp[i][j] = dp[i - 1][j]; |
| 28 | + if (weights[i - 1] <= j) { |
| 29 | + dp[i][j] = Math.max(dp[i][j], values[i - 1] + dp[i - 1][j - weights[i - 1]]); |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + System.out.println("DP knapsack max : " + dp[values.length][W]); |
| 35 | + } |
| 36 | + |
| 37 | + static void rknapsack(int W, int[] values, int[] weights) { |
| 38 | + System.out.println("Recursive knapsack max : " + rdp(W, values, weights, values.length -1)); |
| 39 | + } |
| 40 | + |
| 41 | + static int rdp(int W, int[] values, int[] weights, int i) { |
| 42 | + if (i < 0) return 0; |
| 43 | + int value = rdp(W, values, weights, i - 1); |
| 44 | + if (weights[i] <= W) { |
| 45 | + value = Math.max(value, values[i] + rdp(W - weights[i], values, weights, i - 1)); |
| 46 | + } |
| 47 | + return value; |
| 48 | + } |
| 49 | +} |
0 commit comments