Activity Selection visualization

Pick the most non-overlapping intervals by always taking the one that ends first.

Sort by finish time. Taking the earliest-finishing activity leaves the most room for the rest — an exchange argument proves this is optimal.

Edge cases: touching intervals (one ends exactly when the next starts) are compatible here; identical intervals can only be chosen once; zero-length intervals are fine.

Complexity

Time: best O(n log n), average O(n log n), worst O(n log n). Space: O(n). Difficulty: Beginner.

Pseudocode

procedure selectActivities(intervals):
  sort intervals by end time
  lastEnd ← −∞; chosen ← []
  for (s, e) in intervals:
    if s ≥ lastEnd:
      chosen.append((s, e)); lastEnd ← e
    else: skip — overlaps the previous choice
  return chosen

More greedy algorithms