Greedy Algorithms and Intervals
A greedy rule commits to a local choice whose safety can be justified. Interval problems often expose this rule after sorting endpoints.
Picture the idea
To attend as many nonoverlapping talks as possible, take the available talk that finishes earliest and leave room for the next one.
When to use it
Prove a safe exchange or a staying-ahead invariant. For intervals, specify endpoint semantics first.
How it works
Sort activities by finish time. If an optimal schedule starts with a later-finishing talk, replace it with the earliest finisher; subsequent talks still fit.
- Sort by finish time for selection.
- Accept the next compatible interval.
- Sort by start time for merging.
- Extend the running end when intervals overlap.
Sorting n intervals dominates at O(n log n). Scanning already sorted intervals takes O(n) time.
Watch for this mistake
Earliest finish maximizes the count of compatible talks. Giving talks unequal rewards changes the objective.
Try a small counterexample to an alternative greedy rule such as shortest duration.