Skip to content

Commit 9c50e2f

Browse files
committed
Knapsack 0-1
1 parent 62acf53 commit 9c50e2f

File tree

1 file changed

+31
-0
lines changed
  • datastructure-algorithm-java-examples/src/main/java/com/hellokoding/algorithm

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.hellokoding.algorithm;
2+
3+
public class DP_Knapsack {
4+
int findMaxValueOfKnapSack(int[] values, int[] weights, int W, int N) {
5+
int[][] cache = new int[N+1][W+1];
6+
7+
for (int i = 0; i <= N; i++) {
8+
for (int w = 0; w <= W; w++) {
9+
if (i == 0 || w == 0) {
10+
cache[i][w] = 0;
11+
}
12+
else if (weights[i-1] <= w) {
13+
cache[i][w] = Math.max(cache[i-1][w], cache[i-1][w-weights[i-1]] + values[i-1]);
14+
} else {
15+
cache[i][w] = cache[i-1][w];
16+
}
17+
}
18+
}
19+
20+
return cache[N][W];
21+
}
22+
23+
public static void main(String[] args) {
24+
DP_Knapsack knapsack = new DP_Knapsack();
25+
int[] values = {60, 100, 120};
26+
int[] weights = {10, 20, 30};
27+
int weightLimit = 50;
28+
int noOfItems = values.length;
29+
System.out.println(knapsack.findMaxValueOfKnapSack(values, weights, weightLimit, noOfItems));
30+
}
31+
}

0 commit comments

Comments
 (0)