AlgoVerse

Activity selection

Pick the most activities that do not overlap: always the one that finishes first, if it does not clash with the last one chosen.

We have activities (say, classes in one hall) with a start time s and a finish time f, and want the most of them without overlaps.

Read the full explanation ↓
Input:
activities 11×2PDF export

Eleven activities; four are chosen: [1, 4), [5, 7), [8, 11) and [12, 16).

  1. def activity_selection(activities):
  2. # Each activity is [start, finish); take them in order of finishing time.
  3. acts = sorted(activities, key=lambda a: a[1])
  4. chosen = []
  5. free_from = 0
  6. for start, finish in acts:
  7. if start >= free_from:
  8. chosen.append([start, finish])
  9. free_from = finish
  10. return len(chosen)

Invariant: The chosen activities never overlap, and up to free_from they are at least as many as any optimal answer's.

Start

free_from—

acts

The table is still empty.

chosen

The table is still empty.

Local variables

Orange = changed in this step

activities list

[1, 4][3, 5][0, 6][5, 7][3, 9][5, 9][6, 10][7, 11][8, 12][2, 14][12, 16]

Call stack

  1. activity_selection()line 1
Step 1 of 36
Black = check · Orange = key stepby_finish: 0/1 · check: 0/11 · choose: 0/4
    Explanation

    The idea

    We have activities (say, classes in one hall) with a start time s and a finish time f, and want the most of them without overlaps.

    The greedy choice: sort the activities by finishing time and take each one that starts after the last chosen activity ends.

    Why it works

    The activity that finishes first leaves the most time for the rest. If an optimal answer does not start with it, its first activity can be swapped for this one without any clash; so the greedy choice is always part of some optimal answer.

    Choosing by the earliest start or the shortest length does not always work (see "the longest one first").

    What to watch in the trace

    • The acts table holds the sorted activities and chosen the picks; free_from is when the hall is free again.