GreedyAnimated
Activity Selection
Sort by finish time; take each activity that starts after the last one ends.
Time
O(n log n)
Extra space
O(1)
Use it for
Most non-overlapping events.
How it works
- Sort the activities by finishing time.
- Take the first one. It finishes earliest, so it blocks the least.
- Walk down the list: take an activity only if it starts at or after the end of the last one taken.
- Greedy is optimal here: an exchange argument shows some best schedule always starts with the earliest finisher. O(n log n).
Watch it run
Loading animation…