Algorithms · Activity Selection, Job Sequencing and Greedy Versus Dynamic Programming
Activity Selection Problem
2.1 Statement and notation
Given activities, each with start time and finish time with . Two activities are compatible if their intervals do not overlap: or . (Touching endpoints — one finishes exactly when the next starts — counts as compatible; this is the standard convention in CLRS and in GATE.) Goal: select a maximum-size set of mutually compatible activities.
Notation: = number of activities; = start, finish of activity ; = chosen set; = number of activities selected.
2.2 The greedy rule and why "earliest finish" wins
Rule: sort activities by finish time ascending, then scan once, picking an activity if its start time is the finish time of the last picked activity.
Why earliest finish and not earliest start or shortest duration? Earliest finish leaves the maximum remaining time for all later activities. Formally (exchange argument): let be the activity with earliest finish time in the whole set, and let be an optimal solution. If 's first activity is , then , so replacing by keeps every other activity in compatible (they all start at or after ). So there is an optimal solution starting with ; recurse on the activities starting after . Hence greedy is optimal.
Counter-rules to remember: choosing earliest start or shortest duration first is not optimal in general.
2.3 Algorithm and complexity
ACTIVITY-SELECTION(s, f, n) // f already sorted ascending
1 A = {1}
2 last = 1
3 for i = 2 to n
4 if s[i] >= f[last]
5 A = A ∪ {i}
6 last = i
7 return A
Sorting costs ; the scan is . Total (or if input is already sorted by finish time — a favourite one-mark question).
2.4 Full trace on 8 activities
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | |
|---|---|---|---|---|---|---|---|---|
| 1 | 3 | 0 | 5 | 3 | 5 | 6 | 8 | |
| 4 | 5 | 6 | 7 | 9 | 9 | 10 | 11 |
Step 1 — sort by finish time. Finish times are already in index order, so the sorted order is (ties between 5 and 6 broken arbitrarily; both have ).
Step 2 — scan.
| Step | Consider | ? | Action | last | ||
|---|---|---|---|---|---|---|
| init | 1 | 1 | — | — | pick 1 | 1 () |
| 1 | 2 | 3 | 4 | ? No | skip | 1 |
| 2 | 3 | 0 | 4 | ? No | skip | 1 |
| 3 | 4 | 5 | 4 | ? Yes | pick 4 | 4 () |
| 4 | 5 | 3 | 7 | ? No | skip | 4 |
| 5 | 6 | 5 | 7 | ? No | skip | 4 |
| 6 | 7 | 6 | 7 | ? No | skip | 4 |
| 7 | 8 | 8 | 7 | ? Yes | pick 8 | 8 () |
Answer: , maximum count .
Check compatibility: activity 1 runs , activity 4 runs , activity 8 runs — no overlaps. Can we do 4? The timeline with these intervals: after picking 1 (ends 4) the only activities starting are 4 (5–7), 6 (5–9), 7 (6–10), 8 (8–11). Picking 4 (ends 7) leaves only 8 (starts 8). Picking 6 (ends 9) leaves nothing. So 3 is indeed maximum.