Sub topic 5
Proving Correctness: Greedy Stays Ahead
A greedy algorithm usually looks right at first glance, and many look right while being wrong. The previous chapters showed that a greedy strategy works when it has the greedy choice property and optimal substructure, and that plausible strategies like "largest coin first" can fail. This chapter covers the first of two standard ways to prove that a greedy algorithm is optimal: the greedy-stays-ahead argument.
This chapter assumes you can write a proof by induction and a proof by contradiction, read Python with loops and sorting, and recall the greedy choice property from earlier in the tutorial.
The Core Idea
A greedy algorithm builds its answer one step at a time. An optimal solution can also be read as a sequence of steps. The stays-ahead argument compares the two step by step. It shows that after every step r, the greedy partial solution is at least as good as the optimal one, judged by some chosen measure. If greedy is never behind, it cannot finish behind either, so its final answer is optimal.
The argument is a race between greedy and an unknown optimal solution. You never need to know what the optimal solution looks like. You only need to show that greedy is still level with it or ahead after each step.
The Four-Step Template
Almost every stays-ahead proof follows the same structure.
- Name both solutions. Write the greedy solution as a sequence g₁, g₂, …, gₖ and an arbitrary optimal solution as o₁, o₂, …, oₘ, both in the same natural order (by time, position, or index).
- Choose a measure. Pick a quantity f attached to each prefix, such as "the finish time of the r-th chosen interval" or "the position of the r-th stop."
- Prove the stays-ahead lemma by induction. Show that for every r up to the length of the shorter sequence, f(g₁…gᵣ) is at least as good as f(o₁…oᵣ). The inductive step must use the greedy rule.
- Conclude optimality. Assume greedy is worse overall, usually meaning k > m or k < m, and use the lemma to reach a contradiction.
Worked Example: Fewest Refuelling Stops
The next chapter proves activity selection with this technique. To keep that proof for later, we use a different problem here.
Problem. You drive along a straight road from position 0 to position target. A full tank covers rng kilometres. Petrol stations sit at known positions. You want to reach the target with as few stops as possible, refilling to full at each stop.
Greedy rule. From your current position, drive to the farthest station you can reach, and stop there only if you cannot reach the target directly.
def min_stops(stations, target, rng):
stations = sorted(stations)
stops = []
pos = 0
i = 0
while pos + rng < target:
farthest = None
while i < len(stations) and stations[i] <= pos + rng:
farthest = stations[i]
i += 1
if farthest is None or farthest == pos:
return None # stuck: no station moves us forward
stops.append(farthest)
pos = farthest
return stops
print(min_stops([10, 20, 30, 45, 60, 75], 90, 30)) # [30, 60]Step 1: Name the Solutions
Let the greedy stops be g₁ < g₂ < … < gₖ. Let o₁ < o₂ < … < oₘ be any optimal set of stops. Because O is optimal, m ≤ k. We want to show k = m.
Step 2: Choose the Measure
The measure is the position of the r-th stop. Farther is better, because it leaves more road behind you.
Step 3: The Lemma
Lemma. For every r with 1 ≤ r ≤ m, gᵣ ≥ oᵣ.
Base case (r = 1). The optimal driver reaches o₁ on the first tank, so o₁ ≤ rng. Greedy picks the farthest station within rng of 0, and o₁ is one of the candidates, so g₁ ≥ o₁.
Inductive step. Assume gᵣ₋₁ ≥ oᵣ₋₁. The optimal driver gets from oᵣ₋₁ to oᵣ on one tank, so
oᵣ ≤ oᵣ₋₁ + rng ≤ gᵣ₋₁ + rng.
So oᵣ is within reach of greedy's current position. Greedy chooses the farthest station within reach, so gᵣ ≥ oᵣ. If oᵣ happens to lie behind gᵣ₋₁, the conclusion still holds, because gᵣ > gᵣ₋₁ ≥ oᵣ.
Only the inductive step uses the greedy rule ("farthest reachable"). That is a good sign. A step that never mentions the rule would prove that every algorithm stays ahead, which is false.
Step 4: Conclude
Suppose k > m. The optimal driver reaches the target from its last stop, so target ≤ oₘ + rng. By the lemma, oₘ + rng ≤ gₘ + rng. So at stop gₘ, greedy can already reach the target, the while condition is false, and greedy stops after m stops. That contradicts k > m, so k = m and greedy is optimal.
In the chart, the upper line is greedy and the lower line is another valid two-stop plan. The lemma says no plan's line can rise above greedy's.
Checking the Claim Empirically
A proof is the real guarantee, but a brute-force comparison on small random inputs catches a broken greedy rule fast. Run this check before you invest time in a proof.
import random
from itertools import combinations
def min_stops(stations, target, rng):
stations = sorted(stations)
stops, pos, i = [], 0, 0
while pos + rng < target:
farthest = None
while i < len(stations) and stations[i] <= pos + rng:
farthest = stations[i]
i += 1
if farthest is None or farthest == pos:
return None
stops.append(farthest)
pos = farthest
return stops
def feasible(stops, target, rng):
pos = 0
for s in sorted(stops) + [target]:
if s - pos > rng:
return False
pos = s
return True
def brute_force(stations, target, rng):
for size in range(len(stations) + 1):
for combo in combinations(stations, size):
if feasible(list(combo), target, rng):
return size
return None
random.seed(1)
for _ in range(2000):
target = 50
stations = random.sample(range(1, target), random.randint(0, 8))
rng = random.randint(5, 20)
g = min_stops(stations, target, rng)
b = brute_force(stations, target, rng)
assert (g is None and b is None) or len(g) == b, (stations, rng, g, b)
print("greedy matched brute force on all tests")Choosing a Good Measure
The measure is the creative part of the proof. It must satisfy two conditions. It must be something greedy optimizes locally, so the induction goes through. It must also connect to the final objective, so step 4 works.
| Problem | Measure on the r-th step | "Ahead" means |
|---|---|---|
| Refuelling stops | Position of r-th stop | Greedy's position ≥ optimal's |
| Activity selection | Finish time of r-th chosen interval | Greedy's finish ≤ optimal's |
| Truck loading (boxes in fixed order) | Boxes shipped by the first r trucks | Greedy ships ≥ optimal |
| Dijkstra's algorithm | Distance assigned to the r-th settled vertex | Equals the true shortest distance |
Dijkstra's proof, covered later, is a variant. Instead of comparing two sequences, it shows that each vertex greedy settles already has its final, correct distance.
Common Errors
- Comparing against one particular optimal solution. The proof must work for an arbitrary optimal solution. If you assume the optimum has a convenient shape, you have proved nothing about the others.
- A measure that does not reach the objective. You can prove greedy stays ahead on something irrelevant and then get stuck at step 4. Before starting the induction, check that the final step would follow from the lemma.
- An inductive step that ignores the greedy rule. If the argument would hold for any algorithm, it contains a mistake.
- Index overruns. The lemma only makes sense for r up to min(k, m). Comparing gᵣ with an oᵣ that does not exist is a frequent slip.
- Assuming distinct values. Ties in positions, finish times, or weights can break "strictly ahead" claims. Prove "at least as good" instead.
When to Use Stays Ahead
Stays ahead fits when both solutions are naturally ordered sequences of comparable steps and a single number tracks progress. When the solution is a set or an ordering with no prefix measure, such as a schedule where the order of jobs is the whole answer, the exchange argument in the next chapter usually works better. That argument transforms an optimal solution into the greedy one without making it worse.
Exercise
Change the refuelling greedy to "stop at the nearest station ahead of you whenever you cannot reach the target." Give stations, target and range where it is not optimal, and name the proof step that fails.
Show answer
Stations [10, 20, 30], target 60, range 30. Nearest-first stops at 10, 20 and 30 (3 stops). The optimum stops only at 30 (1 stop). The inductive step fails: knowing g{r-1} ≥ o{r-1} no longer gives gr ≥ or, because the rule does not pick the farthest reachable station. Here g1 = 10 < o1 = 30.
Exercise
Boxes arrive in a fixed order with weights w1, w2, ... and each truck carries at most W. Greedy loads boxes into the current truck until the next one does not fit, then starts a new truck. State the stays-ahead lemma that proves greedy uses the fewest trucks.
Show answer
Let g(r) and o(r) be the number of boxes shipped by the first r trucks in greedy and in any optimal solution. Lemma: g(r) ≥ o(r) for all r. Inductive step: the optimal truck r carries boxes o(r-1)+1 to o(r). Greedy's truck r starts at box g(r-1)+1, which is at or after o(r-1)+1, so boxes g(r-1)+1 to o(r) are a subset of a load that fits, and greedy packs at least those. If the optimum uses m trucks, o(m) is all boxes, so g(m) is all boxes too.
Exercise
Why does the proof say "any optimal solution" instead of "the optimal solution"?
Show answer
There may be several optimal solutions. The lemma must hold against all of them, otherwise an unexamined optimal solution could still beat greedy. Choosing an arbitrary one makes the result general.