Skip to content

Commit ef17a37

Browse files
Create BinaryKnapsack.js
added the js code for Binary Knapsack or 0/1 knapsack problem.
1 parent 55ff0ad commit ef17a37

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Dynamic-Programming/BinaryKnapsack.js

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w]);
12+
} else {
13+
dp[i][w] = dp[i - 1][w];
14+
}
15+
}
16+
}
17+
18+
return dp[n][W];
19+
}
20+
21+
// Driver code
22+
const val = [60, 100, 120];
23+
const wt = [10, 20, 30];
24+
const W = 50;
25+
const n = val.length;
26+
27+
console.log("Maximum value in Knapsack =", knapSack(W, wt, val, n));

0 commit comments

Comments
 (0)