Dynamic programming · Algorithm 15 of 15
0/1 Knapsack
Choose each item at most once while respecting a capacity limit. Citation needed
The whole, before the parts
The 0/1 knapsack problem chooses the most valuable set of items that fits a weight limit, with each item available once. It connects a whole packing decision to smaller choices about which items to include. Citation needed
Terminology and core concepts
Each item has a positive integer weight and a value. Choose a subset with maximum total value whose weight fits a non-negative integer capacity. The “0/1” means each item is either excluded or included once. Let best[c] be the best value fitting capacity c using only items processed so far. For each item, compare skipping it with taking it plus the best value at capacity c - weight from the previous stage. Walking capacities downward preserves that previous-stage answer. Citation needed
Learning path
Trace an example
items (weight, value): (2,3), (3,4), (4,5); capacity 5 capacity 0 1 2 3 4 5 no items 0 0 0 0 0 0 after (2,3) 0 0 3 3 3 3 after (3,4) 0 0 3 4 4 7 after (4,5) 0 0 3 4 5 7
Implement it in Python
Read the loop alongside the trace, then run this self-contained example with Python 3. The assertions show expected results. Inputs use ordinary Python lists and dictionaries; comparisons and numeric operations are assumed to behave normally. Citation needed
def knapsack(items, capacity):
if not isinstance(capacity, int) or capacity < 0:
raise ValueError('capacity must be a non-negative integer')
if any(not isinstance(w, int) or w <= 0 for w, _ in items):
raise ValueError('weights must be positive integers')
best = [0] * (capacity + 1)
for weight, value in items:
for room in range(capacity, weight - 1, -1):
best[room] = max(best[room], best[room - weight] + value)
return best[capacity]
assert knapsack([(2, 3), (3, 4), (4, 5)], 5) == 7
assert knapsack([(2, 3)], 4) == 3 # Cannot use the item twice.
assert knapsack([], 5) == 0
assert knapsack([(2, 3)], 0) == 0Citation needed
Analyze the cost
For n items and capacity C, the bound is O(nC) time plus input validation, and O(C) extra space. This is pseudo-polynomial because C is a numeric capacity rather than its encoded length. It returns an optimal value; recovering the chosen items requires storing additional decisions. Citation needed
A mistake to watch for
Ascending capacity order lets the current item feed its own update, solving the unlimited-copy problem instead. This formulation allows unused capacity and an empty subset; it does not require an exact fill. Citation needed
Practice and recall
-
With only item (2, 3) and capacity 4, why must the answer be 3 rather than 6?
Work it out before opening the solution. Citation needed
Show the reasoning
- At capacity 4, best[2] is still zero because the loop moves downward.
- The update uses zero plus 3, representing one copy.
- Capacity 2 is updated later, so its new value cannot feed capacity 4 in the same pass.
Citation needed
- Why are capacities processed in descending order?
- To avoid using the current item more than once. Citation needed
To check your understanding, reproduce the implementation without looking, explain why its main step is safe, and test an edge case before moving to the next algorithm. Citation needed
Sources
- MIT OpenCourseWare: Introduction to Algorithms — lecture notes — further study of the underlying algorithm and analysis.
- Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein, Introduction to Algorithms — correctness arguments and complexity analysis.