From ef17a373d1f72f2a9643950d88a2974e7454ae7b Mon Sep 17 00:00:00 2001 From: Anurag Sharma <130685870+anurag-sharma17@users.noreply.github.com> Date: Thu, 31 Oct 2024 09:01:44 +0530 Subject: [PATCH] Create BinaryKnapsack.js added the js code for Binary Knapsack or 0/1 knapsack problem. --- Dynamic-Programming/BinaryKnapsack.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Dynamic-Programming/BinaryKnapsack.js diff --git a/Dynamic-Programming/BinaryKnapsack.js b/Dynamic-Programming/BinaryKnapsack.js new file mode 100644 index 0000000000..82f2e0b19e --- /dev/null +++ b/Dynamic-Programming/BinaryKnapsack.js @@ -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));