Skip to content

Commit c93841e

Browse files
committed
Add space optimized 0/1 knapsack implementation
1 parent fc2f947 commit c93841e

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

dynamic_programming/knapsack.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,40 @@ def knapsack(w, wt, val, n):
3939
return dp[n][w_], dp
4040

4141

42+
def knapsack_space_optimized(
43+
capacity: int, weights: list[int], values: list[int], num_items: int
44+
) -> int:
45+
"""
46+
Solve the 0/1 knapsack problem with O(capacity) extra space.
47+
48+
It uses a 1D dynamic programming array and iterates capacities in reverse
49+
for each item to avoid reusing the same item more than once.
50+
51+
>>> knapsack_space_optimized(50, [10, 20, 30], [60, 100, 120], 3)
52+
220
53+
>>> knapsack_space_optimized(0, [10, 20, 30], [60, 100, 120], 3)
54+
0
55+
>>> knapsack_space_optimized(6, [4, 3, 2, 3], [3, 2, 4, 4], 4)
56+
8
57+
"""
58+
if num_items < 0:
59+
raise ValueError("The number of items cannot be negative.")
60+
if capacity < 0:
61+
raise ValueError("The knapsack capacity cannot be negative.")
62+
if num_items > len(weights) or num_items > len(values):
63+
raise ValueError("The number of items exceeds the provided input lengths.")
64+
65+
dp = [0] * (capacity + 1)
66+
for item_index in range(num_items):
67+
item_weight = weights[item_index]
68+
item_value = values[item_index]
69+
for current_capacity in range(capacity, item_weight - 1, -1):
70+
dp[current_capacity] = max(
71+
dp[current_capacity], item_value + dp[current_capacity - item_weight]
72+
)
73+
return dp[capacity]
74+
75+
4276
def knapsack_with_example_solution(w: int, wt: list, val: list):
4377
"""
4478
Solves the integer weights knapsack problem returns one of

0 commit comments

Comments
 (0)