Skip to content
Closed
Changes from all commits
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
42 changes: 42 additions & 0 deletions dynamic_programming/knapsack_memoized_clean.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from functools import cache


def knapsack_memoized(weights: list[int], values: list[int], capacity: int) -> int:
"""
Solve 0/1 knapsack using memoization without global state.

Args:
weights: list of item weights
values: list of item values
capacity: maximum capacity of knapsack

Returns:
Maximum achievable value

>>> knapsack_memoized([1, 3, 4], [10, 20, 30], 4)
30
>>> knapsack_memoized([1, 2, 3], [10, 15, 40], 6)
65
>>> knapsack_memoized([], [], 5)
0
"""

if len(weights) != len(values):
raise ValueError("weights and values must be of same length")

n = len(weights)

@cache
def dp(i: int, remaining: int) -> int:
if i == n or remaining == 0:
return 0

if weights[i] > remaining:
return dp(i + 1, remaining)

return max(
dp(i + 1, remaining),
values[i] + dp(i + 1, remaining - weights[i]),
)

return dp(0, capacity)
Loading