|
9 | 9 | */
|
10 | 10 | public class KnapsackMemoization {
|
11 | 11 |
|
12 |
| - int knapSack(int W, int wt[], int val[], int N) { |
| 12 | + int knapSack(int capacity, int[] weights, int[] profits, int numOfItems) { |
13 | 13 |
|
14 | 14 | // Declare the table dynamically
|
15 |
| - int dp[][] = new int[N + 1][W + 1]; |
| 15 | + int[][] dpTable = new int[numOfItems + 1][capacity + 1]; |
16 | 16 |
|
17 |
| - // Loop to initially filled the |
18 |
| - // table with -1 |
19 |
| - for (int i = 0; i < N + 1; i++) { |
20 |
| - for (int j = 0; j < W + 1; j++) { |
21 |
| - dp[i][j] = -1; |
| 17 | + // Loop to initially fill the table with -1 |
| 18 | + for (int i = 0; i < numOfItems + 1; i++) { |
| 19 | + for (int j = 0; j < capacity + 1; j++) { |
| 20 | + dpTable[i][j] = -1; |
22 | 21 | }
|
23 | 22 | }
|
24 | 23 |
|
25 |
| - return knapSackRec(W, wt, val, N, dp); |
| 24 | + return solveKnapsackRecursive(capacity, weights, profits, numOfItems, dpTable); |
26 | 25 | }
|
27 | 26 |
|
28 |
| - // Returns the value of maximum profit using Recursive approach |
29 |
| - int knapSackRec(int W, int wt[], |
30 |
| - int val[], int n, |
31 |
| - int[][] dp) { |
| 27 | + // Returns the value of maximum profit using recursive approach |
| 28 | + int solveKnapsackRecursive(int capacity, int[] weights, |
| 29 | + int[] profits, int numOfItems, |
| 30 | + int[][] dpTable) { |
32 | 31 |
|
33 | 32 | // Base condition
|
34 |
| - if (n == 0 || W == 0) { |
| 33 | + if (numOfItems == 0 || capacity == 0) { |
35 | 34 | return 0;
|
36 | 35 | }
|
37 | 36 |
|
38 |
| - if (dp[n][W] != -1) { |
39 |
| - return dp[n][W]; |
| 37 | + if (dpTable[numOfItems][capacity] != -1) { |
| 38 | + return dpTable[numOfItems][capacity]; |
40 | 39 | }
|
41 | 40 |
|
42 |
| - if (wt[n - 1] > W) { |
| 41 | + if (weights[numOfItems - 1] > capacity) { |
43 | 42 | // Store the value of function call stack in table
|
44 |
| - dp[n][W] = knapSackRec(W, wt, val, n - 1, dp); |
45 |
| - return dp[n][W]; |
| 43 | + dpTable[numOfItems][capacity] = solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable); |
| 44 | + return dpTable[numOfItems][capacity]; |
46 | 45 | } else {
|
47 | 46 | // Return value of table after storing
|
48 |
| - return dp[n][W] = Math.max((val[n - 1] + knapSackRec(W - wt[n - 1], wt, val, n - 1, dp)), |
49 |
| - knapSackRec(W, wt, val, n - 1, dp)); |
| 47 | + return dpTable[numOfItems][capacity] = Math.max((profits[numOfItems - 1] + solveKnapsackRecursive(capacity - weights[numOfItems - 1], weights, profits, numOfItems - 1, dpTable)), |
| 48 | + solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable)); |
50 | 49 | }
|
51 | 50 | }
|
52 | 51 | }
|
0 commit comments