Sub topic 5
Proving Correctness: Greedy Stays Ahead
This chapter assumes you can do proof by induction and proof by contradiction. It also assumes you can read short Python functions that sort lists. You will learn one of the two standard ways to prove a greedy algorithm optimal. The main idea is to measure greedy's partial solution against an optimal one, step by step, and show that greedy is never behind.
The idea
A greedy algorithm builds its answer one choice at a time. To prove it optimal, you compare it with any optimal solution. If you can show that after every step greedy's partial answer is at least as good as the optimal one's, then greedy cannot finish worse. This is the greedy stays ahead argument.
The argument has four parts:
- Define the two solutions. Write greedy's choices as g1, ..., gk and an optimal solution's as o1, ..., om, both in the order greedy would process them.
- Pick a measure. Choose a number that describes "how well we are doing" after r steps.
- Prove the invariant by induction. Show that greedy's measure is at least as good as the optimal one's for every r.
- Conclude optimality. Use the invariant to rule out the optimal solution being strictly better, usually by contradiction.
Worked proof: earliest finish time
Take the interval scheduling problem. You want the largest set of non-overlapping intervals. Greedy sorts the intervals by finish time and takes each one that starts after the last chosen one ends. The next chapter implements this in detail. Here the goal is to prove it correct.
Sort both solutions by finish time, and let f(x) be the finish time of interval x. The measure is the finish time of the r-th chosen interval, where earlier is better.
Claim. For every r ≤ k, f(gr) ≤ f(or).
- Base case. Greedy's first pick, g1, finishes earliest of all intervals, so f(g1) ≤ f(o1).
- Inductive step. Assume f(g(r−1)) ≤ f(o(r−1)). Since O has no overlaps, o(r−1) ends no later than or starts. So or starts after g(r−1) ends, which means or was still available when greedy made its r-th pick. Greedy takes the available interval that finishes earliest, so f(gr) ≤ f(or).
Optimality. Suppose m > k. By the claim, f(gk) ≤ f(ok), and o(k+1) starts after ok ends. Then o(k+1) was compatible with all of greedy's picks, and greedy would have taken it or something like it instead of stopping. That contradicts greedy having only k intervals, so k = m.
Checking the invariant empirically
A test cannot replace a proof. It can still catch a wrong measure before you spend time proving it. This script compares greedy against a brute-force optimum on random inputs and checks the invariant directly.
import random
from itertools import combinations
def greedy(intervals):
chosen, last_end = [], float("-inf")
for s, e in sorted(intervals, key=lambda iv: iv[1]):
if s >= last_end:
chosen.append((s, e))
last_end = e
return chosen
def compatible(subset):
subset = sorted(subset, key=lambda iv: iv[1])
return all(a[1] <= b[0] for a, b in zip(subset, subset[1:]))
def an_optimum(intervals):
for k in range(len(intervals), 0, -1):
for subset in combinations(intervals, k):
if compatible(subset):
return sorted(subset, key=lambda iv: iv[1])
return []
random.seed(1)
for trial in range(500):
ivs = []
for _ in range(7):
s = random.randint(0, 20)
ivs.append((s, s + random.randint(1, 6)))
g, o = greedy(ivs), an_optimum(ivs)
assert len(g) == len(o), (ivs, g, o)
assert all(g[r][1] <= o[r][1] for r in range(len(g))), (ivs, g, o)
print("Invariant and optimality held in all 500 trials")Common errors
| Mistake | Why it breaks the proof |
|---|---|
| Comparing against one specific optimum | The proof has to hold for any optimal solution, so the argument must be general. |
| Choosing a measure greedy does not control | The inductive step needs greedy's rule to directly imply "not behind". |
| Skipping the "was available" step | You must show or was a legal option for greedy at step r. |
| Stopping at the invariant | Staying ahead is not enough by itself. You still need the final contradiction about size or cost. |
Exercise
Someone proposes "pick the shortest interval first" and tries a stays-ahead proof with the measure "total length used so far." Give a counterexample to the algorithm, and say which step of the proof must fail.
Show answer
Use the intervals (0, 5), (4, 6), (5, 10). Shortest-first picks (4, 6), which overlaps both others, so it ends with 1 interval. The optimum is (0, 5) and (5, 10), which gives 2. The inductive step fails because a short interval can still finish later than or block or. So the earlier picks being shorter does not guarantee that or is still available, and the "was available" step breaks.