Skip to content

Commit e5af4c2

Browse files
Hardvanappgurueu
andauthored
Enhance readability of ZeroOneKnapsack.js (TheAlgorithms#1574)
* Enhance readability of ZeroOneKnapsack.js * Update ZeroOneKnapsack.js --------- Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
1 parent d74f242 commit e5af4c2

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

Dynamic-Programming/ZeroOneKnapsack.js

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,34 @@
11
/**
22
* A Dynamic Programming based solution for calculating Zero One Knapsack
33
* https://en.wikipedia.org/wiki/Knapsack_problem
4+
*
5+
* Time and Space Complexity: O(n*cap)
46
*/
5-
67
const zeroOneKnapsack = (arr, n, cap, cache) => {
8+
// Base Case: No capacity or no items
79
if (cap === 0 || n === 0) {
810
cache[n][cap] = 0
911
return cache[n][cap]
1012
}
13+
14+
// Lookup (value already calculated)
1115
if (cache[n][cap] !== -1) {
1216
return cache[n][cap]
1317
}
18+
19+
// Profit when excluding the nth item
20+
let notPick = zeroOneKnapsack(arr, n - 1, cap, cache)
21+
22+
// Profit when including the nth item
23+
let pick = 0
1424
if (arr[n - 1][0] <= cap) {
15-
cache[n][cap] = Math.max(
16-
arr[n - 1][1] + zeroOneKnapsack(arr, n - 1, cap - arr[n - 1][0], cache),
17-
zeroOneKnapsack(arr, n - 1, cap, cache)
18-
)
19-
return cache[n][cap]
20-
} else {
21-
cache[n][cap] = zeroOneKnapsack(arr, n - 1, cap, cache)
22-
return cache[n][cap]
25+
// If weight of the nth item is within the capacity
26+
pick =
27+
arr[n - 1][1] + zeroOneKnapsack(arr, n - 1, cap - arr[n - 1][0], cache)
2328
}
29+
30+
cache[n][cap] = Math.max(pick, notPick) // maximize profit
31+
return cache[n][cap]
2432
}
2533

2634
const example = () => {

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy