-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
added the js code for Binary Knapsack or 0/1 knapsack problem.
- Loading branch information
1 parent
55ff0ad
commit ef17a37
Showing
1 changed file
with
27 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
function knapSack(W, wt, val, n) { | ||
// Create a 2D DP array to store the maximum value for each subproblem | ||
let dp = Array.from({ length: n + 1 }, () => Array(W + 1).fill(0)); | ||
|
||
// Build table dp[][] in bottom-up manner | ||
for (let i = 0; i <= n; i++) { | ||
for (let w = 0; w <= W; w++) { | ||
if (i === 0 || w === 0) { | ||
dp[i][w] = 0; | ||
} else if (wt[i - 1] <= w) { | ||
dp[i][w] = Math.max(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w]); | ||
} else { | ||
dp[i][w] = dp[i - 1][w]; | ||
} | ||
} | ||
} | ||
|
||
return dp[n][W]; | ||
} | ||
|
||
// Driver code | ||
const val = [60, 100, 120]; | ||
const wt = [10, 20, 30]; | ||
const W = 50; | ||
const n = val.length; | ||
|
||
console.log("Maximum value in Knapsack =", knapSack(W, wt, val, n)); |