Skip to content

Commit a76ead8

Browse files
Create BinaryKnapsack.js
Added the js code for Binary Knapsack or 0/1 Knapsack Problem.
1 parent 55ff0ad commit a76ead8

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Diff for: Dynamic-Programming/BinaryKnapsack.js

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
function knapSack(W, wt, val, n) {
2+
// Create a 2D DP array to store the maximum value for each subproblem
3+
let dp = Array.from({ length: n + 1 }, () => Array(W + 1).fill(0));
4+
5+
// Build table dp[][] in bottom-up manner
6+
for (let i = 0; i <= n; i++) {
7+
for (let w = 0; w <= W; w++) {
8+
if (i === 0 || w === 0) {
9+
dp[i][w] = 0;
10+
} else if (wt[i - 1] <= w) {
11+
dp[i][w] = Math.max(
12+
val[i - 1] + dp[i - 1][w - wt[i - 1]],
13+
dp[i - 1][w]
14+
);
15+
} else {
16+
dp[i][w] = dp[i - 1][w];
17+
}
18+
}
19+
}
20+
21+
return dp[n][W];
22+
}
23+
24+
// Driver code
25+
const val = [60, 100, 120];
26+
const wt = [10, 20, 30];
27+
const W = 50;
28+
const n = val.length;
29+
30+
console.log("Maximum value in Knapsack =", knapSack(W, wt, val, n));

0 commit comments

Comments
 (0)