TExcelTAD

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 nn requests. Request aia_i wants the hall during the half-open interval [si,fi)[s_i, f_i), from its start time up to but not including its finish time. Two activities are compatible if their intervals do not overlap: [si,fi)[s_i, f_i) and [sj,fj)[s_j, f_j) are compatible when fi≤sjf_i \le s_j or fj≤sif_j \le s_i. 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 ss 1 2 4 3 6 7 9 8 10 12
finish ff 3 5 7 8 9 10 11 13 14 15
text
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 aia_i and aja_j, let SijS_{ij} be the activities that start after aia_i finishes and finish before aja_j starts. Add sentinel activities a0a_0 with f0=0f_0 = 0 and an+1a_{n+1} with sn+1=∞s_{n+1} = \infty, so that S0,n+1S_{0,n+1} is the whole input. If a maximum compatible subset of SijS_{ij} contains some aka_k, it splits into a maximum subset of SikS_{ik}, then aka_k, then a maximum subset of SkjS_{kj}, and the usual cut-and-paste argument shows both parts must be optimal. With c[i,j]c[i, j] the size of a maximum subset of SijS_{ij}:

c[i,j]={0if Sij=∅,max⁡ak∈Sij(c[i,k]+c[k,j]+1)otherwise.c[i, j] = \begin{cases} 0 & \text{if } S_{ij} = \emptyset, \\ \max\limits_{a_k \in S_{ij}} \bigl( c[i, k] + c[k, j] + 1 \bigr) & \text{otherwise.} \end{cases}

That is an interval DP with Θ(n2)\Theta(n^2) subproblems and up to nn choices each, O(n3)O(n^3) time. It works:

python · try it yourself
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 SS be a nonempty set of activities and let ama_m be one with the earliest finish time in SS. Then ama_m belongs to some maximum-size compatible subset of SS.

Proof (an exchange argument). Let AA be any maximum compatible subset of SS, and let aja_j be the activity of AA with the earliest finish time. If aj=ama_j = a_m, done. Otherwise replace aja_j by ama_m: let A′=(A∖{aj})∪{am}A' = (A \setminus \{a_j\}) \cup \{a_m\}. Every other activity of AA starts no earlier than fjf_j (they are compatible with aja_j and finish after it), and fm≤fjf_m \le f_j, so they are all compatible with ama_m too. Hence A′A' is compatible, and ∣A′∣=∣A∣\lvert A' \rvert = \lvert A \rvert, so A′A' is a maximum subset that contains ama_m. ■\blacksquare

The theorem changes everything. In the DP, the subproblem SijS_{ij} had to try every aka_k. 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 SS finishes before ama_m does). So the table collapses into a single scan:

  1. pick the activity that finishes first;
  2. discard everything that overlaps it;
  3. repeat on what is left.

That is the greedy algorithm, and on sorted input it takes Θ(n)\Theta(n) 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.

python · try it yourself
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 [3,5)[3, 5) against [0,4)[0, 4) and [4,8)[4, 8). 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, [0,4)[0, 4) to [12,16)[12, 16), one activity [7,9)[7, 9) 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 [7,9)[7, 9) 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.

cpp · try it yourself
#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?

  1. The one that starts first
  2. The shortest one
  3. The one that finishes first
  4. The one with the fewest conflicts

In the exchange argument, aja_j is the first-finishing activity of an optimal set AA, and ama_m is the first-finishing activity overall. Why is (A∖{aj})∪{am}(A \setminus \{a_j\}) \cup \{a_m\} still compatible?

  1. Because ama_m is shorter than aja_j
  2. Because every other activity of AA starts at or after fj≥fmf_j \ge f_m
  3. Because ama_m starts before aja_j
  4. Because AA has only one activity

For activities [0,4)[0, 4), [3,5)[3, 5) and [4,8)[4, 8), how many does the rule 'shortest first' schedule, and what is the optimum?

  1. 1 and 2
  2. 2 and 2
  3. 1 and 1
  4. 2 and 3