The problem
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.
Rule: take the talk that starts first. That is [0, 6), and it holds the room until 6. After it only [6, 10) fits. 2 talks, but 3 are possible. A greedy algorithm needs the right rule.
Earliest finish first
The rule that works: earliest finish first. Line 2 sorts the talks by finish time, so the rows now run from the talk that ends first to the one that ends last. Ending early leaves the most room for the rest.
last starts at 0. The first talk, [1, 4), starts at 1, and 1 ≥ 0, so it fits: add it and set last to its finish, 4. The fence marks last: a talk fits only if it starts at or after it.
[3, 5) starts at 3, before the fence at 4: it would overlap [1, 4), so skip it. [0, 6) starts at 0: skip it too. A skipped talk is never looked at again.
[5, 7) starts at 5, and 5 ≥ 4: it fits after [1, 4). Add it and move the fence to 7. Because the talks are sorted, this is the talk that fits and ends soonest.
[6, 10) starts at 6, before 7: skip. [8, 11) starts at 8 ≥ 7: take it. One pass, each talk checked once. The answer lane holds 3 talks side by side, with no overlap.
Why it works
Take any best answer, say [3, 5), [5, 7), [8, 11). Its first talk ends at 5. Greedy's first ends at 4, no later, so swap it in: nothing new clashes and the count stays 3. Some best answer starts with greedy's pick.
After the first pick, what remains is the same problem, smaller: the talks that start at 4 or later. The same swap works there, and after every pick. So greedy never falls behind a best answer: it is optimal.
Sorting n talks takes O(n log n) time; Python's sort is Timsort, a merge sort relative. The loop then checks each talk once: O(n). Total: O(n log n), or O(n) if the talks already come sorted by finish time.
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.