Skip to content

Enhance readability of ZeroOneKnapsack.js #1574

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 30, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Enhance readability of ZeroOneKnapsack.js
  • Loading branch information
Hardvan committed Oct 24, 2023
commit c5fb8dbc07210f902a6c6b9af356e2e3e96df3c0
26 changes: 18 additions & 8 deletions Dynamic-Programming/ZeroOneKnapsack.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,34 @@
* https://en.wikipedia.org/wiki/Knapsack_problem
*/

// Memoization Approach (Top Down) for calculating Zero One Knapsack
// Time Complexity: O(n*cap)
// Space Complexity: O(n*cap)
const zeroOneKnapsack = (arr, n, cap, cache) => {
// Base Case ()
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]
}

// Exclude the nth item
let notPick = zeroOneKnapsack(arr, n - 1, cap, cache)

// Include 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)
return cache[n][cap]
}

const example = () => {
Expand Down