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