01234567891011123–55–78–111def schedule(talks):2 talks.sort(key=lambda t: t[1])3 last, out = 0, []4 for s, f in talks:5 if s >= last:6 out.append((s, f))7 last = f8 return outlastlen(out)last5–70–68–111–46–103–51–4
Bars: one talk each, from its start hour to its finish hourFence: the value of last; a talk fits if it starts at or after itAnswer lane: the talks greedy takes, side by sideSix talks on a 0 to 12 hour timeline, one room. Sorted by finish time and scanned once, each talk that starts at or after the fence (the variable last) hops into the answer lane, and the fence moves to its finish: 1–4, 5–7, 8–11. Swapping greedy's first pick into another best answer keeps it clash-free, which is why earliest finish first is optimal.

The problem

  1. Each bar is a talk: it starts at one hour and ends at another. There is one room, so two talks clash if their bars overlap. The goal: fit in as many talks as possible, with no clashes.

Earliest finish first

Why it works

What happens

;; step 1/10 · problem
talks, in the order they arrive (start, finish):
  (5, 7) (0, 6) (8, 11) (1, 4) (6, 10) (3, 5)

a talk is the half-open interval [s, f):
[1, 4) and [4, 6) do not clash
best possible here: 3 talks (checked over all 64 subsets)

Talks are half-open intervals [s, f): a talk that ends at 4 and one that starts at 4 do not clash. That is why the test is s >= last and not s > last (MIT 6.046 and CLRS use the same convention). The proof follows MIT 6.046 (lecture 1) and CLRS §15.1 (§16.1 in the 3rd edition): swap the first talk of any best answer for the earliest-finishing talk, then apply the same argument to the talks that start after it, by induction.