File tree 1 file changed +26
-0
lines changed
1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class Knapsack {
2
+ public int knapsack (int cap , int [] weights , int [] values ) {
3
+ int n = values .length ;
4
+ // Base case: Set the first column and last row to 0 by
5
+ // initializing the entire DP table to 0.
6
+ int [][] dp = new int [n + 1 ][cap + 1 ];
7
+
8
+ // Populate the DP table.
9
+ for (int i = n - 1 ; i >= 0 ; i --) {
10
+ for (int c = 1 ; c < cap + 1 ; c ++) {
11
+ // If the item 'i' fits in the current knapsack capacity,
12
+ // the maximum value at 'dp[i][c]' is the largest of either:
13
+ // 1. The maximum value if we include item 'i'.
14
+ // 2. The maximum value if we exclude item 'i'.
15
+ if (weights [i ] <= c ) {
16
+ dp [i ][c ] = Math .max (values [i ] + dp [i + 1 ][c - weights [i ]], dp [i + 1 ][c ]);
17
+ }
18
+ // If it doesn't fit, we have to exclude it.
19
+ else {
20
+ dp [i ][c ] = dp [i + 1 ][c ];
21
+ }
22
+ }
23
+ }
24
+ return dp [0 ][cap ];
25
+ }
26
+ }
You can’t perform that action at this time.
0 commit comments