|
| 1 | +import java.util.HashMap; |
| 2 | +import java.util.Map; |
| 3 | + |
| 4 | +// Time complexity: O(nW) where n is the number of items in the input and W is the Knapsack capacity. |
| 5 | +// Auxilary space: O(nW) |
| 6 | + |
| 7 | +class KnapSack |
| 8 | +{ |
| 9 | + // Values (stored in array v) |
| 10 | + // Weights (stored in array w) |
| 11 | + // Number of distinct items (n) |
| 12 | + // Knapsack capacity W |
| 13 | + public static int knapSack(int[] v, int[] w, int n, int W, |
| 14 | + Map<String, Integer> lookup) |
| 15 | + { |
| 16 | + // base case: Negative capacity |
| 17 | + if (W < 0) { |
| 18 | + return Integer.MIN_VALUE; |
| 19 | + } |
| 20 | + |
| 21 | + // base case: no items left or capacity becomes 0 |
| 22 | + if (n < 0 || W == 0) { |
| 23 | + return 0; |
| 24 | + } |
| 25 | + |
| 26 | + // construct a unique map key from dynamic elements of the input |
| 27 | + String key = n + "|" + W; |
| 28 | + |
| 29 | + // if sub-problem is seen for the first time, solve it and |
| 30 | + // store its result in a map |
| 31 | + if (!lookup.containsKey(key)) |
| 32 | + { |
| 33 | + // Case 1. include current item n in knapSack (v[n]) & recur |
| 34 | + // for remaining items (n-1) with decreased capacity (W - w[n]) |
| 35 | + int include = v[n] + knapSack(v, w, n - 1, W - w[n], lookup); |
| 36 | + |
| 37 | + // Case 2. exclude current item n from knapSack and recur for |
| 38 | + // remaining items (n-1) |
| 39 | + int exclude = knapSack(v, w, n - 1, W, lookup); |
| 40 | + |
| 41 | + // assign max value we get by including or excluding current item |
| 42 | + lookup.put(key, Integer.max(include, exclude)); |
| 43 | + } |
| 44 | + |
| 45 | + // return solution to current sub-problem |
| 46 | + return lookup.get(key); |
| 47 | + } |
| 48 | + |
| 49 | + // 0-1 Knapsack problem |
| 50 | + public static void main(String[] args) |
| 51 | + { |
| 52 | + // Input: set of items each with a weight and a value |
| 53 | + int[] v = { 20, 5, 10, 40, 15, 25 }; |
| 54 | + int[] w = { 1, 2, 3, 8, 7, 4 }; |
| 55 | + |
| 56 | + // Knapsack capacity |
| 57 | + int W = 10; |
| 58 | + |
| 59 | + // create a map to store solutions of subproblems |
| 60 | + Map<String, Integer> lookup = new HashMap<>(); |
| 61 | + |
| 62 | + System.out.println("Knapsack value is " + |
| 63 | + knapSack(v, w, v.length - 1, W, lookup)); |
| 64 | + } |
| 65 | +} |
0 commit comments