Sub topic 3
Optimal Substructure
This chapter assumes you can read recursive Python functions, know what an interval schedule is, and have read the previous chapter on the greedy choice property.
The Second Ingredient
The greedy choice property says that one locally best choice can start an optimal solution. That choice still leaves you with a smaller problem to solve. Optimal substructure is the guarantee that solving that smaller problem optimally, and adding it to your first choice, gives an optimal solution to the whole problem.
Stated precisely, a problem has optimal substructure when an optimal solution contains optimal solutions to its subproblems. If you take any piece of an optimal answer and look at the subproblem that piece solves, that piece must be the best answer to that subproblem.
A greedy algorithm needs both properties:
| Property | What it guarantees |
|---|---|
| Greedy choice property | The first greedy choice belongs to some optimal solution |
| Optimal substructure | The rest of the solution can be found by solving the remaining subproblem optimally |
Seeing It in Activity Selection
In activity selection, suppose you pick the interval that finishes first, call it f. The intervals that start at or after f ends form a subproblem. The claim is that f plus the best schedule for that subproblem is the best schedule overall.
The proof uses contradiction. Suppose the optimal schedule is {f} ∪ R, and R is not the best answer for the subproblem. Then some larger compatible set R' exists. Every interval in R' starts after f ends, so {f} ∪ R' is also valid and larger than the optimal schedule, which is impossible. This "cut and paste" pattern is the standard way to prove optimal substructure.
The code below checks this claim on a small input by comparing the greedy recursion against brute force:
from itertools import combinations
def compatible(subset):
s = sorted(subset, key=lambda iv: iv[1])
return all(a[1] <= b[0] for a, b in zip(s, s[1:]))
def brute_force(intervals):
for k in range(len(intervals), 0, -1):
for subset in combinations(intervals, k):
if compatible(subset):
return list(subset)
return []
def greedy_recursive(intervals):
if not intervals:
return []
first = min(intervals, key=lambda iv: iv[1])
rest = [iv for iv in intervals if iv[0] >= first[1]]
return [first] + greedy_recursive(rest)
data = [(1, 4), (3, 5), (0, 6), (5, 7), (3, 9), (5, 9), (6, 10), (8, 11)]
print(len(greedy_recursive(data)), len(brute_force(data))) # 3 3
first = (1, 4)
rest = [iv for iv in data if iv[0] >= first[1]]
print(len(brute_force(rest))) # 2, one fewer than the full optimumThe recursive structure of greedy_recursive follows the definition directly: one choice, then the same function applied to the subproblem.
When the Property Is Missing
Optimal substructure is easy to assume without checking. Shortest paths have it: any part of a shortest path is itself a shortest path between its endpoints. Longest simple paths do not. The longest simple path from A to C may pass through B, while the longest path from A to B on its own might go through C. You cannot join the two, because the result would visit C twice. The subproblems interfere with each other, so breaking the problem apart doesn't work.
Exercise
In the fractional knapsack problem with capacity W, you take as much as possible of the item with the highest value per weight, using w units. State the remaining subproblem and explain why its optimal solution, combined with your first choice, is optimal overall.
Show answer
The remaining subproblem is the same set of items, minus what you already took, with capacity W - w. If the optimal overall solution used a non-optimal filling of that remaining capacity, you could swap in the better filling. It fits in W - w, so it doesn't conflict with the first choice, and the swap would raise the total value. That contradicts optimality, so the remainder must be solved optimally.
Exercise
Why does the longest simple path problem lack optimal substructure?
Show answer
Combining optimal solutions to two subpaths, A to B and B to C, can produce a path that repeats a vertex. That path is not simple, so it is not a valid solution. The subproblems share resources (vertices) and are not independent.