Activity Selection
Dynamic programming tries every choice and keeps the best. Often that is necessary, but sometimes one choice is always safe, and you can commit to it without looking at the alternatives. An algorithm that repeatedly makes the choice that looks best right now and never revisits it is greedy. Greedy algorithms are short and fast, and they are wrong more often than they are right, so each one needs a proof. This lesson takes the first classic example, activity selection, sets it up as a DP, and then proves that one specific greedy choice can replace the whole table.
The problem
A single lecture hall receives requests. Request wants the hall during the half-open interval , from its start time up to but not including its finish time. Two activities are compatible if their intervals do not overlap: and are compatible when or . Choose a largest set of pairwise compatible activities. The running example, already sorted by finish time:
| activity | B | A | C | D | E | F | G | H | I | J |
|---|---|---|---|---|---|---|---|---|---|---|
| start | 1 | 2 | 4 | 3 | 6 | 7 | 9 | 8 | 10 | 12 |
| finish | 3 | 5 | 7 | 8 | 9 | 10 | 11 | 13 | 14 | 15 |
time 0 2 4 6 8 10 12 14
B [=====)
A [=======)
C [=======)
D [===========)
E [=====)
F [=====)
G [=====)
H [==========)
I [========)
J [=====)A dynamic program first
For two activities and , let be the activities that start after finishes and finish before starts. Add sentinel activities with and with , so that is the whole input. If a maximum compatible subset of contains some , it splits into a maximum subset of , then , then a maximum subset of , and the usual cut-and-paste argument shows both parts must be optimal. With the size of a maximum subset of :
That is an interval DP with subproblems and up to choices each, time. It works:
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)]
INF = float("inf")
s = [None, ] + [a[1] for a in acts] + [INF] # sentinels at 0 and n + 1
f = [0] + [a[2] for a in acts] + [None]
n = len(acts)
c = [[0] * (n + 2) for _ in range(n + 2)]
choice = [[None] * (n + 2) for _ in range(n + 2)]
steps = 0
for gap in range(2, n + 2): # by increasing j - i
for i in range(0, n + 2 - gap):
j = i + gap
for k in range(i + 1, j):
steps += 1
if s[k] >= f[i] and f[k] <= s[j] and c[i][k] + c[k][j] + 1 > c[i][j]:
c[i][j], choice[i][j] = c[i][k] + c[k][j] + 1, k
def collect(i, j):
k = choice[i][j]
return [] if k is None else collect(i, k) + [acts[k - 1][0]] + collect(k, j)
print("maximum number of activities:", c[0][n + 1])
print("one optimal set:", collect(0, n + 1), " (DP steps:", steps, ")")maximum number of activities: 4
one optimal set: ['B', 'C', 'F', 'I'] (DP steps: 220 )
The DP finds 4 activities. But look at which ones: it starts with B, the activity that finishes first. That is not an accident.
The greedy choice
Theorem. Let be a nonempty set of activities and let be one with the earliest finish time in . Then belongs to some maximum-size compatible subset of .
Proof (an exchange argument). Let be any maximum compatible subset of , and let be the activity of with the earliest finish time. If , done. Otherwise replace by : let . Every other activity of starts no earlier than (they are compatible with and finish after it), and , so they are all compatible with too. Hence is compatible, and , so is a maximum subset that contains .
The theorem changes everything. In the DP, the subproblem had to try every . Now we know that choosing the earliest-finishing activity is always safe, and after choosing it only one subproblem remains: the activities that start after it finishes (the subproblem before it is empty, since nothing in finishes before does). So the table collapses into a single scan:
- pick the activity that finishes first;
- discard everything that overlaps it;
- repeat on what is left.
That is the greedy algorithm, and on sorted input it takes time, the subject of the next lesson.
Other greedy rules fail
The proof used a specific property of "earliest finish": it frees the hall as early as possible, leaving the most room for the rest. Three other natural rules look just as plausible, and all three are wrong. The program searches small random instances for a counterexample to each, comparing with a brute-force optimum. Ties are broken in favour of the earlier finish time, so a failure is never just bad luck with ties.
import random
from itertools import combinations
def compatible(chosen):
chosen = sorted(chosen, key=lambda a: a[0])
return all(x[1] <= y[0] for x, y in zip(chosen, chosen[1:]))
def optimum(acts):
for k in range(len(acts), 0, -1):
if any(compatible(c) for c in combinations(acts, k)):
return k
return 0
def greedy(acts, key):
chosen = []
for a in sorted(acts, key=lambda a: (key(a), a[1])): # ties: earlier finish first
if compatible(chosen + [a]):
chosen.append(a)
return len(chosen)
rules = {
"earliest finish": lambda a: a[1],
"shortest first": lambda a: a[1] - a[0],
"earliest start": lambda a: a[0],
}
rng = random.Random(2)
for name, rule in rules.items():
found = None
for _ in range(3000):
acts = []
for _ in range(rng.randint(2, 7)):
st = rng.randint(0, 12)
acts.append((st, st + rng.randint(1, 6)))
if greedy(acts, rule) < optimum(acts):
found = sorted(acts)
break
print(f"{name:16}: " + (f"fails on {found}" if found else "no counterexample in 3000 tries"))
# "fewest conflicts first": a hand-built instance where the rule has no ties to hide behind
acts = [(0, 4), (4, 8), (8, 12), (12, 16), (7, 9),
(3, 5), (3, 6), (2, 5), (11, 13), (10, 13), (11, 14)]
conflicts = lambda a: sum(1 for b in acts if b != a and not compatible([a, b]))
print("fewest conflicts: conflict counts", {a: conflicts(a) for a in acts[:5]})
print(f"fewest conflicts: schedules {greedy(acts, conflicts)}, optimum {optimum(acts)}")earliest finish : no counterexample in 3000 tries
shortest first : fails on [(0, 2), (1, 5), (4, 9), (6, 10), (8, 13), (9, 15)]
earliest start : fails on [(0, 6), (1, 4), (1, 5), (4, 5), (8, 12), (10, 16)]
fewest conflicts: conflict counts {(0, 4): 3, (4, 8): 4, (8, 12): 4, (12, 16): 3, (7, 9): 2}
fewest conflicts: schedules 3, optimum 4
Earliest finish survives 3000 random trials, as the theorem promises, and the other two rules fail quickly. A smallest counterexample for "shortest first" is easy to remember: a short activity that straddles the boundary between two long compatible ones, like against and . The rule "fewest conflicts first" is harder to break, and small random instances tend to defeat it only through ties. The hand-built instance has four compatible activities in a row, to , one activity with only 2 conflicts straddling the middle boundary, and clusters of overlapping activities that inflate the conflict counts of the four good ones. The rule takes first and can then fit only two more. Testing a greedy rule against brute force on small random inputs is the quickest way to kill a wrong idea before trying to prove it.
In C++
The interval DP in C++ on the same ten activities, as a reference for checking the greedy algorithm of the next lesson.
#include <cstdio>
#include <vector>
int main() {
const double INF = 1e18;
std::vector<double> s = {0, 1, 2, 4, 3, 6, 7, 9, 8, 10, 12, INF}; // sentinel a_0 and a_11
std::vector<double> f = {0, 3, 5, 7, 8, 9, 10, 11, 13, 14, 15, INF};
int n = 10;
std::vector<std::vector<int>> c(n + 2, std::vector<int>(n + 2, 0));
for (int gap = 2; gap <= n + 1; ++gap)
for (int i = 0; i + gap <= n + 1; ++i) {
int j = i + gap;
for (int k = i + 1; k < j; ++k)
if (s[k] >= f[i] && f[k] <= s[j] && c[i][k] + c[k][j] + 1 > c[i][j])
c[i][j] = c[i][k] + c[k][j] + 1;
}
std::printf("maximum number of compatible activities: %d\n", c[0][n + 1]);
}maximum number of compatible activities: 4
Test yourself
Which activity does the greedy choice for activity selection pick first?
- The one that starts first
- The shortest one
- The one that finishes first
- The one with the fewest conflicts
In the exchange argument, is the first-finishing activity of an optimal set , and is the first-finishing activity overall. Why is still compatible?
- Because is shorter than
- Because every other activity of starts at or after
- Because starts before
- Because has only one activity
For activities , and , how many does the rule 'shortest first' schedule, and what is the optimum?
- 1 and 2
- 2 and 2
- 1 and 1
- 2 and 3