Sub topic 5
Take It or Leave It: Deriving the Recurrence
The earlier chapters showed two dead ends. Trying every subset gives the right answer, but the work doubles with each added item. Picking items greedily by value-per-weight is fast, but it can miss the best answer when items cannot be split. This chapter finds a middle path. It describes the problem as a chain of small yes-or-no decisions, then shows that the best answer to the whole problem is built from the best answers to smaller versions of it. The resulting equation is called the recurrence, and every dynamic programming solution in the rest of the tutorial is built on it.
This chapter assumes you can read Python functions and recursion, know Big-O notation, and remember the 0/1 problem statement: there are n items, item i has value values[i] and weight weights[i], each item is used at most once, and the total weight must not go over capacity.
The Decision for One Item
Look only at item 0. Any valid packing either contains item 0 or does not. There is no third option, and that observation is the whole idea.
- Leave it. The best result is whatever you can get from items 1 to n−1 with the full capacity still free.
- Take it. This is only allowed if
weights[0] <= capacity. You gainvalues[0], and the remaining items must fit incapacity - weights[0].
Each branch leaves a smaller problem behind: fewer items to consider, and possibly less space. Applying the same split to that smaller problem, over and over, covers every possible packing without listing them one by one.
Defining the Subproblem
To write this as an equation, you need a name for "a smaller version of the problem." Two numbers describe one fully:
i, the index of the next item to decide on. Itemsithroughn-1are still open, and the earlier items are already settled.c, the capacity still free.
Define f(i, c) as the largest total value you can get from items i, i+1, ..., n-1 using at most c units of weight. The answer to the original problem is f(0, capacity).
The pair (i, c) is called the state. It must hold everything that affects the future and nothing more. The future does not depend on which earlier items you took. It depends only on how much room they left, so the state does not need to store that history.
The Recurrence
Writing the two branches as formulas gives:
- Base case: f(n, c) = 0 for every c ≥ 0. With no items left, you can add no value.
- If
weights[i] > c: f(i, c) = f(i+1, c). Item i does not fit, so leaving it is the only choice. - Otherwise: f(i, c) = max( f(i+1, c), values[i] + f(i+1, c − weights[i]) ).
| Case | Condition | Value of f(i, c) |
|---|---|---|
| No items left | i = n | 0 |
| Item too heavy | weights[i] > c | f(i+1, c) |
| Item fits | weights[i] ≤ c | max(f(i+1, c), values[i] + f(i+1, c − weights[i])) |
Both recursive calls move to i+1. That is what makes this the 0/1 recurrence: once you decide on item i, you never see it again.
Why the Recurrence Is Correct: Optimal Substructure
The max looks only at the best value of each smaller problem. Why is it safe to throw away every other way of solving them? The reason is a property called optimal substructure: an optimal solution to the whole problem contains optimal solutions to the smaller problems inside it.
The proof uses a cut-and-paste argument. Let S be an optimal packing for state (i, c), and suppose S contains item i. Remove item i from S. The items left over, call them S′, fit in c − weights[i] and come from items i+1 onward. Now suppose S′ were not optimal for (i+1, c − weights[i]), meaning some packing T does strictly better there. Then T plus item i fits in c and is worth more than S, which contradicts S being optimal. So S′ must be optimal for its smaller problem. The same argument works when S leaves item i out, using the state (i+1, c).
So the optimum always equals one of the two branch values, each computed optimally, and taking the max of the two finds it. The greedy method had no such guarantee. It committed to one choice and never compared it against the other.
Tracing the Example
Use the example from the earlier chapters: values [60, 100, 120], weights [10, 20, 30], capacity 50. Greedy by ratio scored 160 on this input.
Work from the bottom up. f(2, 20) = 0 because item 2 does not fit. f(1, 40) = max(120, 100 + 0) = 120. f(1, 50) = max(120, 100 + 120) = 220. At the root, f(0, 50) = max(220, 60 + 120) = 220. The best packing skips item 0 and takes items 1 and 2.
The Recurrence as Code
The function below translates the recurrence line for line. It also counts the calls and records which distinct states it visits.
def knapsack_rec(values, weights, capacity):
n = len(values)
calls = 0
states = set()
def best(i, c):
nonlocal calls
calls += 1
states.add((i, c))
if i == n:
return 0
skip = best(i + 1, c)
if weights[i] <= c:
take = values[i] + best(i + 1, c - weights[i])
return max(skip, take)
return skip
return best(0, capacity), calls, len(states)
print(knapsack_rec([60, 100, 120], [10, 20, 30], 50)) # (220, 14, 14)
print(knapsack_rec([1] * 18, [1] * 18, 18)) # (18, 524287, 190)On the small input, every call visits a new state. On the second input, 18 identical items, the function makes 524,287 calls but meets only 190 distinct states. The reason is that different decision paths lead to the same state. Taking item 0 and skipping item 1 leaves (2, 17), and so does skipping item 0 and taking item 1. This is called overlapping subproblems, and it is why plain recursion takes exponential time: it solves the same state again every time a path reaches it.
There are at most (n+1)(capacity+1) states in total. If each one is solved only once, the work drops to O(n · capacity). The next two chapters do exactly that, first by caching results (memoization) and then by filling a table.
Common Mistakes
- Skipping the fit check. If you call the take branch when
weights[i] > c, the capacity goes negative. You then either get an index error or a "solution" that overflows the knapsack. Either guard the call, as above, or add a base case that returns negative infinity when c < 0. - Staying on the same item. Writing
best(i, c - weights[i])in the take branch lets you take item i again. That solves the unbounded problem, covered in a later chapter, not the 0/1 problem. - Putting too much in the state. Passing the list of chosen items as an argument makes almost every call unique, so caching can no longer help. The state should contain only what the future depends on.
- Wrong base case. f(n, c) must be 0 for every c, not only for c = 0. Leftover capacity is allowed.
Prefix Form
The table-based chapter uses an equivalent formulation that works on prefixes instead of suffixes. Define g(i, c) as the best value using only the first i items. Then g(0, c) = 0, and g(i, c) = max(g(i−1, c), values[i−1] + g(i−1, c − weights[i−1])) when item i−1 fits. The logic is the same, except the decisions run from the last item back to the first. Both forms give the same answer.
Exercise
Using the recurrence, compute f(0, 5) for values [3, 4, 5] and weights [2, 3, 4]. Which items are taken?
Show answer
f(2, c) = 5 if c ≥ 4, else 0. For f(1, 5), take item 1: 4 + f(2, 2) = 4, or skip it: f(2, 5) = 5, so f(1, 5) = 5. For f(1, 3), take item 1: 4 + f(2, 0) = 4, or skip it: f(2, 3) = 0, so f(1, 3) = 4. At the root, f(0, 5) = max(f(1, 5), 3 + f(1, 3)) = max(5, 7) = 7. The best packing takes items 0 and 1, with weight 5 and value 7.
Exercise
A colleague changes the take branch to values[i] + best(i, c - weights[i]). What does the function compute now, and what does it return for values [60, 100, 120], weights [10, 20, 30], capacity 50?
Show answer
Item i stays available after being taken, so the function now solves the unbounded knapsack, where each item can be reused. It returns 300, from five copies of item 0 (5 × 60 with weight 50).
Exercise
Why does the state not need to record which items were taken before index i?
Show answer
Earlier choices affect the remaining problem only through the capacity they used up, and c already records that. The values and weights of items i onward do not depend on past choices, so two paths that reach the same (i, c) face the same remaining problem and have the same best answer.