Skip to content

Commit b0d5bc9

Browse files
committed
add: KnapsackOptimized
1 parent 44dffe0 commit b0d5bc9

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
}

0 commit comments

Comments
 (0)