Activity selection
To fit the most non-overlapping activities, sort by finishing time and keep taking the next one that starts after the last chosen one ends. Finishing early leaves the most room for the rest. When jobs have profits or deadlines instead, sort by profit and give each job the latest free slot, or switch to dynamic programming when profits make the greedy choice unsafe.
How to recognise it
- Intervals, meetings or jobs, and the question asks for the most that fit.
- Each job takes one slot and has a deadline and a profit.
- An order of processing must be chosen to make waiting time small.
The classic: most activities in one room
sort activities by end time
lastEnd = -infinity
for each activity:
if start > lastEnd: take it; lastEnd = end
The first activity to finish can always be part of a best answer: if a best answer starts with something else, swap it for the earliest finisher and nothing clashes. Repeat the argument for what is left. This swap argument is how most greedy proofs go.
Whether touching activities clash (start equal to the last end) depends on the problem. Read it, and use > or >=.
Variants in this section
| Problem | Sort by | Then |
|---|---|---|
| N meetings, activity selection | end time | take if it starts after the last end |
| trains on platforms | departure | the same rule per platform |
| job sequencing | profit, highest first | put each job in the latest free slot before its deadline |
| shortest job first | length, shortest first | everyone waits for the jobs before them |
| weighted job scheduling | end time | DP: skip the job, or take it after the last compatible one |
Common mistakes
- Sorting by start time or by length.
- Using the greedy when each job has a different value; that needs DP.
- Mixing up strict and non-strict comparisons at the boundary.
Problems
- Shortest Job Firstmediumguide ready
- Job sequencing Problemmediumguide ready
- N meetings in one roommediumguide ready
- Job Scheduling Algomediumguide ready
- Activity Selection Problemmediumguide ready
- Maximum trains for which stoppage can be providedmediumguide ready