Skip to content

Commit bb9e865

Browse files
921vikramVikram Prakash
and
Vikram Prakash
authored
Add Memoization solution for knapsack (TheAlgorithms#2560)
Co-authored-by: Vikram Prakash <vpsahu@juniper.net>
1 parent 71a735f commit bb9e865

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package DynamicProgramming;
2+
3+
4+
import java.util.Arrays;
5+
6+
/**
7+
* Recursive Solution for 0-1 knapsack with memoization
8+
*/
9+
public class KnapsackMemoization {
10+
11+
private static int[][] t;
12+
13+
14+
// Returns the maximum value that can
15+
// be put in a knapsack of capacity W
16+
public static int knapsack(int[] wt, int[] value, int W, int n) {
17+
if(t[n][W] != -1) {
18+
return t[n][W];
19+
}
20+
if (n == 0 || W == 0) {
21+
return 0;
22+
}
23+
if (wt[n - 1] <= W) {
24+
t[n-1][W-wt[n-1]] = knapsack(wt, value, W - wt[n - 1], n - 1);
25+
// Include item in the bag. In that case add the value of the item and call for the remaining items
26+
int tmp1 = value[n - 1] + t[n-1][W-wt[n-1]];
27+
// Don't include the nth item in the bag anl call for remaining item without reducing the weight
28+
int tmp2 = knapsack(wt, value, W, n - 1);
29+
t[n-1][W] = tmp2;
30+
// include the larger one
31+
int tmp = tmp1 > tmp2 ? tmp1 : tmp2;
32+
t[n][W] = tmp;
33+
return tmp;
34+
// If Weight for the item is more than the desired weight then don't include it
35+
// Call for rest of the n-1 items
36+
} else if (wt[n - 1] > W) {
37+
t[n][W] = knapsack(wt, value, W, n - 1);
38+
return t[n][W];
39+
}
40+
return -1;
41+
}
42+
43+
// Driver code
44+
public static void main(String args[]) {
45+
int[] wt = {1, 3, 4, 5};
46+
int[] value = {1, 4, 5, 7};
47+
int W = 10;
48+
t = new int[wt.length+1][W+1];
49+
Arrays.stream(t).forEach(a -> Arrays.fill(a, -1));
50+
int res = knapsack(wt, value, W, wt.length);
51+
System.out.println("Maximum knapsack value " + res);
52+
}
53+
}

0 commit comments

Comments
 (0)