Greedy Algorithms & the Night Scheduler
In short: a greedy algorithm builds its answer one piece at a time, always taking whatever looks best right now, and never revisiting that choice. That makes greedy code short — usually a sort plus one loop — but it is only correct when the problem has the greedy-choice property: some best answer really does begin with the greedy choice. Prove that with an exchange argument, or test it against brute force on small cases. Get the rule wrong and greedy still runs, it just quietly returns a worse answer.

Booking Friday's main stage
Tunebox Live has one stage and a pile of DJs who want it. Each sent a set
with a start and an end time, two sets can't share the stage, and the
booker wants as many sets as possible. Sort by finish time, keep
free_at (when the stage is next free), and book anything that starts at
or after it:
Earliest finish first: each booking leaves as much of the night free as possible for the sets still to come.
Nova finishes first, at 20, so she is booked and the stage is free again from 20. 5 by 6 table. At row 0, column 0 — value ■. 10 of 30 cells filled.
The mistake: "best-looking" is doing a lot of work in that sentence. Earliest start sounds just as fair — first come, first served — and it fails badly:
Shortest-first fails too: three sets [18–21], [20–22], [21–24] — the
short middle one clashes with both neighbours, so booking it first blocks
the two long sets that would otherwise fit together. Only earliest finish
is safe. Take any best schedule and look at its first set. The set that
finishes earliest overall, E, ends no later than that first set does — so
swap them in. Nothing after it can clash, you still have the same number of
sets, and now the schedule starts with the greedy choice. Repeat the
argument for the rest of the night and greedy keeps pace with the optimum
all the way through. That's the exchange argument: show any optimal
answer can be rewritten to start with the greedy choice without getting
worse. Write that paragraph and the greedy is proven; if you can't, what you
have is a hunch.
A back-to-back set — one that starts exactly when the previous one ends — doesn't share a single minute of stage time, and the comparison has to allow that:
All three back-to-back sets should be booked, so this should print 3. It prints 2.
Coming from Java/JS: the sort is the whole trick —
sets.sort((a, b) => a[2] - b[2])in JS,Arrays.sort(sets, Comparator.comparingInt(s -> s[2]))in Java. Python'skey=computes one key per item instead of comparing pairs. All three sorts are stable: equal keys keep their input order, and the task relies on that.