Learn / Greedy

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

ProblemSort byThen
N meetings, activity selectionend timetake if it starts after the last end
trains on platformsdeparturethe same rule per platform
job sequencingprofit, highest firstput each job in the latest free slot before its deadline
shortest job firstlength, shortest firsteveryone waits for the jobs before them
weighted job schedulingend timeDP: 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

0 of 6 solved

Check yourself

Meetings (1, 2), (3, 4), (0, 6), (5, 7), (8, 9), (5, 9). How many fit in one room if a meeting must start after the last one ends?

Why sort by end time and not by start time?

In job sequencing, which slot should a job take?

Why can weighted job scheduling not use the end-time greedy?