From e5af4c24b4156279827f6a6cc4349f70247a53f2 Mon Sep 17 00:00:00 2001 From: Hardik Pawar <97388607+Hardvan@users.noreply.github.com> Date: Mon, 30 Oct 2023 11:04:06 +0530 Subject: [PATCH] Enhance readability of ZeroOneKnapsack.js (#1574) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Enhance readability of ZeroOneKnapsack.js * Update ZeroOneKnapsack.js --------- Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com> --- Dynamic-Programming/ZeroOneKnapsack.js | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/Dynamic-Programming/ZeroOneKnapsack.js b/Dynamic-Programming/ZeroOneKnapsack.js index 3913d016b..52a06aa13 100644 --- a/Dynamic-Programming/ZeroOneKnapsack.js +++ b/Dynamic-Programming/ZeroOneKnapsack.js @@ -1,26 +1,34 @@ /** * A Dynamic Programming based solution for calculating Zero One Knapsack * https://en.wikipedia.org/wiki/Knapsack_problem + * + * Time and Space Complexity: O(n*cap) */ - const zeroOneKnapsack = (arr, n, cap, cache) => { + // Base Case: No capacity or no items if (cap === 0 || n === 0) { cache[n][cap] = 0 return cache[n][cap] } + + // Lookup (value already calculated) if (cache[n][cap] !== -1) { return cache[n][cap] } + + // Profit when excluding the nth item + let notPick = zeroOneKnapsack(arr, n - 1, cap, cache) + + // Profit when including the nth item + let pick = 0 if (arr[n - 1][0] <= cap) { - cache[n][cap] = Math.max( - arr[n - 1][1] + zeroOneKnapsack(arr, n - 1, cap - arr[n - 1][0], cache), - zeroOneKnapsack(arr, n - 1, cap, cache) - ) - return cache[n][cap] - } else { - cache[n][cap] = zeroOneKnapsack(arr, n - 1, cap, cache) - return cache[n][cap] + // If weight of the nth item is within the capacity + pick = + arr[n - 1][1] + zeroOneKnapsack(arr, n - 1, cap - arr[n - 1][0], cache) } + + cache[n][cap] = Math.max(pick, notPick) // maximize profit + return cache[n][cap] } const example = () => {