easy

Activity Selection

You are given n activities, each with a start and finish time, and a single resource that can host one activity at a time. Select the maximum number of activities that do not overlap in time.

Constraints
  • 1 ≤ n ≤ 10^5
  • 0 ≤ start < finish ≤ 10^9
Examples
in: start = [1,3,0,5,8,5], finish = [2,4,6,7,9,9]
out: 4
Activities ending at 2, 4, 7, 9.
Recognition clues
  • Maximum number of compatible intervals
  • Picking the activity that finishes earliest leaves the most room
  • Sort by finish time, single pass
Pattern
Greedy

When a locally best choice (earliest finish time, largest ratio, farthest reach) can be proved never to hurt the global optimum, you can commit to it without exploring alternatives and get O(n log n) from sorting. The proof usually comes via an exchange argument; if you cannot sketch one, suspect DP instead.

Solution

Sort activities by finish time. Take the first one, then scan the rest and select each activity whose start is at least the finish time of the last selected one. The exchange argument shows that any optimal solution can be rewritten to begin with the earliest-finishing activity without losing a selection, so the greedy choice is safe at every step.

time O(n log n)space O(1)
Alternative approaches
  • Sorting by start time or by duration are both wrong. Weighted activity selection needs DP with binary search in O(n log n).
Code it yourself
Solve in
Hints:
Learn Activity Selection