Skip to content

Commit 08bfc1a

Browse files
committed
Refactor: clean memoized knapsack using functools.cache
1 parent 841e947 commit 08bfc1a

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from functools import cache
2+
3+
4+
def knapsack_memoized(weights: list[int], values: list[int], capacity: int) -> int:
5+
"""
6+
Solve 0/1 knapsack using memoization without global state.
7+
8+
Args:
9+
weights: list of item weights
10+
values: list of item values
11+
capacity: maximum capacity of knapsack
12+
13+
Returns:
14+
Maximum achievable value
15+
16+
>>> knapsack_memoized([1, 3, 4], [10, 20, 30], 4)
17+
30
18+
>>> knapsack_memoized([1, 2, 3], [10, 15, 40], 6)
19+
65
20+
>>> knapsack_memoized([], [], 5)
21+
0
22+
"""
23+
24+
if len(weights) != len(values):
25+
raise ValueError("weights and values must be of same length")
26+
27+
n = len(weights)
28+
29+
@cache
30+
def dp(i: int, remaining: int) -> int:
31+
if i == n or remaining == 0:
32+
return 0
33+
34+
if weights[i] > remaining:
35+
return dp(i + 1, remaining)
36+
37+
return max(
38+
dp(i + 1, remaining),
39+
values[i] + dp(i + 1, remaining - weights[i]),
40+
)
41+
42+
return dp(0, capacity)

0 commit comments

Comments
 (0)