Greedy Activity Selection, Recursive and Iterative
The previous lesson proved that the activity finishing first always belongs to some optimal schedule. This lesson turns that theorem into code twice: first as a recursion that mirrors the proof (choose, then solve the one remaining subproblem), then as the loop that everyone actually writes. Then it gives a second, independent proof of correctness, the "greedy stays ahead" argument, and applies the same ideas to a related problem: how many halls do you need to run all the activities?
The recursive version
Assume the activities are numbered in order of finish time, , and add a sentinel with . A call with index solves the subproblem "activities that start after finishes": it skips activities that start too early, takes the first one that fits (the earliest finishing activity of the subproblem), and recurses on what is left after it.
RECURSIVE-SELECT(s, f, k, n) // activities k+1..n are candidates; a_k was the last one chosen
1 m = k + 1
2 while m <= n and s[m] < f[k] // skip activities that overlap a_k
3 m = m + 1
4 if m <= n
5 return {a_m} union RECURSIVE-SELECT(s, f, m, n)
6 else return empty setThe first call is RECURSIVE-SELECT(s, f, 0, n). Each activity is examined exactly once across all calls, because each call continues where the previous one stopped: time on sorted input.
acts = [("B", 1, 3), ("A", 2, 5), ("C", 4, 7), ("D", 3, 8), ("E", 6, 9),
("F", 7, 10), ("G", 9, 11), ("H", 8, 13), ("I", 10, 14), ("J", 12, 15)]
names = [None] + [a[0] for a in acts]
s = [None] + [a[1] for a in acts]
f = [0] + [a[2] for a in acts] # f[0] = 0 is the sentinel
n = len(acts)
def recursive_select(k, depth=0):
m = k + 1
while m <= n and s[m] < f[k]:
print(" " * depth + f"skip {names[m]} [{s[m]}, {f[m]}): starts before {f[k]}")
m += 1
if m <= n:
print(" " * depth + f"take {names[m]} [{s[m]}, {f[m]})")
return [names[m]] + recursive_select(m, depth + 1)
return []
print("chosen:", recursive_select(0))take B [1, 3)
skip A [2, 5): starts before 3
take C [4, 7)
skip D [3, 8): starts before 7
skip E [6, 9): starts before 7
take F [7, 10)
skip G [9, 11): starts before 10
skip H [8, 13): starts before 10
take I [10, 14)
skip J [12, 15): starts before 14
chosen: ['B', 'C', 'F', 'I']
The recursion is a tail call: the recursive call is the last thing that happens, and its result is only prepended to. Every tail recursion turns mechanically into a loop.
The iterative version
GREEDY-SELECT(s, f, n) // activities sorted by finish time
1 A = {a_1}
2 k = 1 // the last activity added
3 for m = 2 to n
4 if s[m] >= f[k] // a_m starts after a_k ends
5 A = A union {a_m}
6 k = m
7 return Adef greedy_select(activities):
"""activities: (name, start, finish) in any order; returns a maximum compatible set"""
chosen, last_finish = [], float("-inf")
for name, start, finish in sorted(activities, key=lambda a: a[2]):
if start >= last_finish:
chosen.append(name)
last_finish = finish
return chosen
acts = [("A", 2, 5), ("B", 1, 3), ("C", 4, 7), ("D", 3, 8), ("E", 6, 9),
("F", 7, 10), ("G", 9, 11), ("H", 8, 13), ("I", 10, 14), ("J", 12, 15)]
print("greedy:", greedy_select(acts))
# compare with brute force on random instances
import random
from itertools import combinations
def best_count(acts):
for k in range(len(acts), 0, -1):
for c in combinations(sorted(acts, key=lambda a: a[1]), k):
if all(x[2] <= y[1] for x, y in zip(c, c[1:])):
return k
return 0
rng = random.Random(4)
ok = True
for trial in range(300):
inst = [(str(i), st, st + rng.randint(1, 5)) for i, st in enumerate(rng.randint(0, 15) for _ in range(rng.randint(0, 9)))]
ok &= len(greedy_select(inst)) == best_count(inst)
print("greedy is optimal on 300 random instances:", ok)greedy: ['B', 'C', 'F', 'I']
greedy is optimal on 300 random instances: True
With the sort, the whole algorithm takes ; the greedy scan itself is . Note the test start >= last_finish: activities are half-open intervals, so one can begin at the exact moment the previous one ends. Writing > instead is the most common bug in this algorithm, and the practice problem Activity Selection tests that case.
In C++
#include <algorithm>
#include <cstdio>
#include <string>
#include <vector>
struct Activity { std::string name; int start, finish; };
std::vector<std::string> greedy_select(std::vector<Activity> acts) {
std::sort(acts.begin(), acts.end(), [](const Activity& a, const Activity& b) { return a.finish < b.finish; });
std::vector<std::string> chosen;
int last_finish = -1000000000;
for (const auto& a : acts)
if (a.start >= last_finish) { chosen.push_back(a.name); last_finish = a.finish; }
return chosen;
}
int main() {
std::vector<Activity> acts = {{"A", 2, 5}, {"B", 1, 3}, {"C", 4, 7}, {"D", 3, 8}, {"E", 6, 9},
{"F", 7, 10}, {"G", 9, 11}, {"H", 8, 13}, {"I", 10, 14}, {"J", 12, 15}};
auto chosen = greedy_select(acts);
std::printf("%zu activities:", chosen.size());
for (const auto& name : chosen) std::printf(" %s", name.c_str());
std::printf("\n");
}4 activities: B C F I
The mirror image
Nothing in the problem prefers the left end of the time line. Reverse time, and "finishes first" becomes "starts last": choosing the activity with the latest start, discarding what overlaps it and repeating is optimal too, by the same exchange argument run backwards. The two rules usually pick different activities but always the same number of them.
import random
def earliest_finish(acts):
chosen, free_at = [], float("-inf")
for name, s, f in sorted(acts, key=lambda a: a[2]):
if s >= free_at:
chosen.append(name); free_at = f
return chosen
def latest_start(acts):
chosen, busy_from = [], float("inf")
for name, s, f in sorted(acts, key=lambda a: -a[1]):
if f <= busy_from:
chosen.append(name); busy_from = s
return chosen[::-1]
acts = [("A", 2, 5), ("B", 1, 3), ("C", 4, 7), ("D", 3, 8), ("E", 6, 9),
("F", 7, 10), ("G", 9, 11), ("H", 8, 13), ("I", 10, 14), ("J", 12, 15)]
print("earliest finish:", earliest_finish(acts))
print("latest start: ", latest_start(acts))
rng = random.Random(30)
same = 0
for _ in range(1000):
inst = [(str(i), s, s + rng.randint(1, 6)) for i, s in enumerate(rng.randint(0, 20) for _ in range(rng.randint(1, 12)))]
same += len(earliest_finish(inst)) == len(latest_start(inst))
print("same number of activities on", same, "of 1000 random instances")earliest finish: ['B', 'C', 'F', 'I']
latest start: ['A', 'E', 'G', 'J']
same number of activities on 1000 of 1000 random instances
On the running example the two rules have no activity in common: earliest finish takes B, C, F, I, latest start takes A, E, G, J, four each. Both are optimal, which is a reminder that "the greedy solution" is one optimal solution among possibly many.
A second proof: greedy stays ahead
The exchange argument modified an optimal solution until it agreed with greedy. A different style of proof compares the two solutions step by step and shows that greedy is never behind.
Let greedy choose and let be any compatible set, both listed in order of finish time.
Lemma. For every , .
Proof by induction on . For , greedy picks the activity with the earliest finish overall, so . For : by induction , the second inequality because and are compatible. So was still available when greedy made its -th choice, and greedy picked the available activity that finishes first: .
Theorem. . Proof. If , then starts after , so it was still available after greedy's last choice, and greedy would not have stopped.
Both proofs are standard, and it is worth knowing both: exchange arguments generalise to matroids (Matroids), while "stays ahead" arguments are often easier for scheduling problems.
Related: how many halls for all activities?
Change the question: every activity must happen, and you may open several halls. What is the fewest number of halls? Call the depth of the instance the largest number of activities that overlap at one moment. Clearly you need at least that many halls. Greedy achieves it: process activities by start time, and put each one in any hall that is free at its start, opening a new hall only if none is. A min-heap of the halls' finish times finds a free hall in .
import heapq
acts = [("A", 2, 5), ("B", 1, 3), ("C", 4, 7), ("D", 3, 8), ("E", 6, 9),
("F", 7, 10), ("G", 9, 11), ("H", 8, 13), ("I", 10, 14), ("J", 12, 15)]
halls = [] # heap of (finish time of the hall's last activity, hall number)
assignment, opened = {}, 0
for name, start, finish in sorted(acts, key=lambda a: a[1]):
if halls and halls[0][0] <= start:
_, h = heapq.heappop(halls) # reuse the hall that frees up first
else:
opened += 1
h = opened # open a new hall
assignment[name] = h
heapq.heappush(halls, (finish, h))
depth = max(sum(1 for _, s, f in acts if s <= t < f) for t in range(16))
print("halls used:", opened, " depth:", depth)
for h in range(1, opened + 1):
print(f"hall {h}:", [n for n, _, _ in sorted(acts, key=lambda a: a[1]) if assignment[n] == h])halls used: 3 depth: 3
hall 1: ['B', 'D', 'H']
hall 2: ['A', 'E', 'G', 'J']
hall 3: ['C', 'F', 'I']
The number of halls equals the depth, so it is optimal. Why: a new hall is opened only for an activity that starts while every existing hall is busy; at that moment the existing halls' current activities and all overlap time , so the depth is at least the new number of halls.
Test yourself
Why does RECURSIVE-SELECT take only time on sorted input, although it may skip many activities per call?
- Because it only recurses once per chosen activity, and the skipping loops of all calls together examine each activity once
- Because it uses memoization
- Because the input has at most activities
- It does not; it takes
Activities , , , . How many does greedy (earliest finish, start >= last_finish) choose?
- 1
- 2
- 3
- 4
In the 'greedy stays ahead' proof, what does the lemma state?
- Greedy's -th activity starts no later than the optimum's -th
- Greedy's -th activity finishes no later than any compatible set's -th activity
- Greedy and the optimum choose the same activities
- Greedy's activities are the shortest ones