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
The best value is 7 by taking weights 2 and 3; the single weight-4 item gives only 5.

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) == 0

Citation 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

  1. 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
    1. At capacity 4, best[2] is still zero because the loop moves downward.
    2. The update uses zero plus 3, representing one copy.
    3. 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