mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 01:18:23 +08:00
Enhance readability of ZeroOneKnapsack.js (#1574)
* Enhance readability of ZeroOneKnapsack.js * Update ZeroOneKnapsack.js --------- Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
This commit is contained in:
@ -1,26 +1,34 @@
|
|||||||
/**
|
/**
|
||||||
* A Dynamic Programming based solution for calculating Zero One Knapsack
|
* A Dynamic Programming based solution for calculating Zero One Knapsack
|
||||||
* https://en.wikipedia.org/wiki/Knapsack_problem
|
* https://en.wikipedia.org/wiki/Knapsack_problem
|
||||||
|
*
|
||||||
|
* Time and Space Complexity: O(n*cap)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const zeroOneKnapsack = (arr, n, cap, cache) => {
|
const zeroOneKnapsack = (arr, n, cap, cache) => {
|
||||||
|
// Base Case: No capacity or no items
|
||||||
if (cap === 0 || n === 0) {
|
if (cap === 0 || n === 0) {
|
||||||
cache[n][cap] = 0
|
cache[n][cap] = 0
|
||||||
return cache[n][cap]
|
return cache[n][cap]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Lookup (value already calculated)
|
||||||
if (cache[n][cap] !== -1) {
|
if (cache[n][cap] !== -1) {
|
||||||
return cache[n][cap]
|
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) {
|
if (arr[n - 1][0] <= cap) {
|
||||||
cache[n][cap] = Math.max(
|
// If weight of the nth item is within the capacity
|
||||||
arr[n - 1][1] + zeroOneKnapsack(arr, n - 1, cap - arr[n - 1][0], cache),
|
pick =
|
||||||
zeroOneKnapsack(arr, n - 1, cap, cache)
|
arr[n - 1][1] + zeroOneKnapsack(arr, n - 1, cap - arr[n - 1][0], cache)
|
||||||
)
|
|
||||||
return cache[n][cap]
|
|
||||||
} else {
|
|
||||||
cache[n][cap] = zeroOneKnapsack(arr, n - 1, cap, cache)
|
|
||||||
return cache[n][cap]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
cache[n][cap] = Math.max(pick, notPick) // maximize profit
|
||||||
|
return cache[n][cap]
|
||||||
}
|
}
|
||||||
|
|
||||||
const example = () => {
|
const example = () => {
|
||||||
|
Reference in New Issue
Block a user