Pattern visualizer
Activity Selection Problem
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. Animated on: activities = (1,2),(3,4),(0,6),(5,7),(5,9),(8,9) — pick the maximum number of non-overlapping activities..
Sort by end time, always take what finishes soonest
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