Interval Scheduling
You're the office manager and you have one conference room. Employees keep submitting meeting requests, each with a start and end time. You want to fit in as many meetings as possible — they just can't overlap.
Which meetings do you pick? Here's the counterintuitive insight: always pick the meeting that ends earliest. Not the shortest. Not the earliest to start. The one that finishes first.
The Greedy Algorithm
1. Sort all meetings by finish time (ascending).
2. Pick the first meeting. Mark its finish time as your current "last used" time.
3. Scan the rest: if a meeting starts at or after the last finish time, take it and update last finish.
4. Skip any meeting that starts before the current last finish (it would overlap).
That's it. One sort + one linear scan = \(O(n \log n)\) total.
Why Not Sort by Start Time or Duration?
Sort by start time: A meeting that starts at 9am but runs until 6pm blocks everything. Early start ≠ leaving time for others.
Sort by duration: A 30-minute meeting might overlap with ten others. A 1-hour meeting might conflict with none. Short doesn't mean compatible.
Sort by finish time: This is the right criterion. Choosing the meeting that ends soonest leaves the maximum remaining window for future meetings. The exchange argument makes this rigorous.
Proof by Exchange Argument
Suppose an optimal schedule OPT doesn't start with the earliest-finishing meeting G. Let A be OPT's first pick. Since G finishes no later than A, we can swap A → G in OPT. G doesn't conflict with any later meeting that A didn't conflict with (it finishes at least as early). The schedule size doesn't decrease. Repeat until OPT matches greedy. So greedy is optimal.
Interval Partitioning (Bonus Variant)
What if you want to schedule all meetings but minimize the number of rooms used? Greedy again: sort by start time, assign each meeting to any available room. If none are free, open a new room. The minimum rooms needed equals the maximum depth — the largest number of overlapping meetings at any instant. A sweep-line with a min-heap computes this in \(O(n \log n)\).
Weighted Interval Scheduling (When Greedy Fails)
Add profits to meetings and maximize total profit instead of count. Now greedy fails — a highly profitable 8-hour meeting might be worth more than four 1-hour meetings. This variant needs Dynamic Programming: sort by finish time, define dp[j] = best profit using meetings 1..j, use binary search to find the last non-conflicting meeting.