Activity Selection
Sort by end time, always take what finishes soonest
Among all activities that don't conflict with what's already picked, the one that ends soonest always leaves the most room for future picks — it can never do worse than any other valid choice. So sort by end time once, then greedily take any activity whose start doesn't collide with the last one taken; no backtracking is ever needed.
Details
Animated on: activities = (1,2),(3,4),(0,6),(5,7),(5,9),(8,9) — pick the maximum number of non-overlapping activities.
Problem:Activity SelectionMedium
Sort by end time, always take what finishes soonest
step 1 / 8
Sort activities by END time: (1,2), (3,4), (0,6), (5,7), (5,9), (8,9). Picking whichever finishes earliest always leaves the most room for what's left.
1FUNCTION activitySelection(activities):2 sort activities by end time3 selected = empty list, lastEnd = negative infinity4 FOR each activity with start and end in activities:5 IF start >= lastEnd:6 add [start, end] to selected (no overlap)7 lastEnd = end8 RETURN selected
← / → step · space play · Home restart
Every step in words
Show all 8 steps
- Sort activities by END time: (1,2), (3,4), (0,6), (5,7), (5,9), (8,9). Picking whichever finishes earliest always leaves the most room for what's left.
- (1,2): starts at 1 >= lastEnd(none yet) — no overlap, pick it. lastEnd = 2.
- (3,4): starts at 3 >= lastEnd(2) — no overlap, pick it. lastEnd = 4.
- (0,6): starts at 0 < lastEnd(4) — overlaps the last pick, skip it.
- (5,7): starts at 5 >= lastEnd(4) — no overlap, pick it. lastEnd = 7.
- (5,9): starts at 5 < lastEnd(7) — overlaps the last pick, skip it.
- (8,9): starts at 8 >= lastEnd(7) — no overlap, pick it. lastEnd = 9.
- Selected 4 non-overlapping activities: (1,2), (3,4), (5,7), (8,9).
Now solve it yourself
Watching is the first half. The second is writing it without the animation.