Skip to content

Commit 933db30

Browse files
committed
add: Knapsack
1 parent dd0c0a8 commit 933db30

File tree

1 file changed

+26
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)