Greedy interval scheduling
A greedy strategy makes a locally chosen move, and it works only when that move can be justified.
How it works
Sort by end, then keep a finish time for the last selected meeting. If another meeting starts at that time or later, it fits. For equal finish times either candidate leaves the same time available for later meetings. This is why the choice can be evaluated by end time instead of length.
Walk through an example
To schedule as many nonoverlapping meetings as possible, take the meeting that ends earliest, then repeat with meetings starting at or after its end. An earlier finish leaves at least as much room as a later one.
What to watch for
The same rule does not maximize total meeting value when meetings have different weights. That version needs another approach, often dynamic programming.
Code example
def select(intervals):
chosen = []
for start, end in sorted(intervals, key=lambda pair: pair[1]):
if not chosen or start >= chosen[-1][1]:
chosen.append((start, end))
return chosenCheck your understanding
Which intervals does earliest finish select?
See the example and explanation
- Worked example
- Given
[1,4), [2,3), [3,5) - Answer
[2,3) and [3,5)
The interval ending at 3 is selected first. The next one starts exactly when it ends.