Sub topic 5
Take It or Leave It: Deriving the Recurrence
This chapter assumes you know basic Python recursion, can read Big-O notation, and have seen the 0/1 knapsack problem defined. It also assumes you have seen why greedy selection by value-to-weight ratio can fail. Here we build the rule that every dynamic programming solution to the 0/1 knapsack rests on.
Naming the Subproblem
The first step is to choose a subproblem small enough to reason about and general enough to contain the full problem. For items numbered 0 to n-1, define:
best(i, c)is the maximum total value you can get using only itemsi, i+1, ..., n-1with remaining capacityc.
The answer to the original problem is best(0, W), where W is the knapsack capacity. Each state needs two numbers: the item you are deciding on next, and the capacity you have left.
Optimal Substructure
Take any optimal selection S for the state (i, c). Item i is either in S or it is not.
- Item
iis not inS. ThenSuses only itemsi+1onward and fits in capacityc. It must be optimal for(i+1, c). If some better selection existed there, it would also be valid for(i, c)and would beatS. - Item
iis inS. Remove it. What remains fits inc - w[i]and uses itemsi+1onward. It must be optimal for(i+1, c - w[i]). A better remainder plus itemiwould beatS.
This is the cut-and-paste argument: an optimal solution is made of optimal solutions to smaller subproblems. You don't know in advance which case holds, so you try both and keep the larger value.
The Recurrence
| Condition | `best(i, c)` |
|---|---|
| `i == n` (no items left) | `0` |
| `w[i] > c` (item does not fit) | `best(i+1, c)` |
| otherwise | `max(best(i+1, c), v[i] + best(i+1, c - w[i]))` |
The middle row is easy to forget. Without it, the "take" branch would reach a negative capacity.
Running the Recurrence Directly
The code below is the recurrence written as plain recursion with nothing cached. It also counts how many calls it makes.
calls = 0
def best(i, c, values, weights):
global calls
calls += 1
if i == len(values):
return 0
skip = best(i + 1, c, values, weights)
if weights[i] > c:
return skip
take = values[i] + best(i + 1, c - weights[i], values, weights)
return max(skip, take)
print(best(0, 50, [60, 100, 120], [10, 20, 30])) # 220
print(calls) # 15Trace the top level by hand. best(1, 50) is 220, from taking items 1 and 2. best(1, 40) is 120, because items 1 and 2 together weigh 50 and only one of them fits. Taking item 0 therefore gives 60 + 120 = 180, and the maximum of the two branches is 220.
Common Errors
- Letting capacity go negative. Check
w[i] > cbefore taking the item. Alternatively, return negative infinity whenc < 0. - Returning to the same item after taking it. The "take" branch moves to
i+1. If it stayed ati, you would be solving the unbounded variant. - Using the wrong base case. With no items left, the value is
0for every capacity, including0.
Exercise
Using values [60, 100, 120], weights [10, 20, 30], compute best(0, 30) by hand with the recurrence. Which items are chosen?
Show answer
best(0, 30) = max(best(1, 30), 60 + best(1, 20)). best(1, 30) = max(best(2, 30), 100 + best(2, 10)) = max(120, 100 + 0) = 120. best(1, 20) = max(best(2, 20), 100 + best(2, 0)) = max(0, 100) = 100, so taking item 0 gives 160. The answer is 160, from items 0 and 1, which weigh 30 in total.
Exercise
Why does the recurrence need a separate case for w[i] > c instead of always computing both branches?
Show answer
When the item does not fit, the take branch would call best(i+1, c - w[i]) with a negative capacity. That state means nothing, and the code could return a value for a selection that does not fit. The separate case allows only the skip branch.