Skip to content

Activity selection

planning ahead

Level 1 of 3

Also called Interval scheduling and Earliest finish time first.

how it works

The idea on the watch page's first example, four activities and one room. Then the whole method on it, step by step.

A runs from 0 to 6, B from 1 to 2, C from 3 to 4 and D from 5 to 7. The room holds one at a time. Two activities clash when each starts before the other ends. Two that only touch, one ending as the next starts, do not clash. Earliest start first takes A. A runs till 6 and clashes with B, C and D: 1 activity. Earliest finish first takes B, then C, then D: 3, the most, as section 4's question 4 shows. So line the activities up by the hour each ends, earliest first: B, C, A, D. Take each in turn. Choose it if it starts once the last one chosen has ended, and rule it out if not. The table below walks it. Lining them up is a sort, and the watch page's sort is merge sort. It merges the ends, typed 6, 2, 4, 7, in pairs. 6 with 2 takes 1 comparison, 4 with 7 takes 1, then 2, 6 with 4, 7 takes 3: 2 against 4, 6 against 4, 6 against 7. That is 5 comparisons. Then each activity after the first is checked once against the room's free hour: 3 checks. This page counts the comparisons, the dearer part. The code below lines them up with Python's own sort and returns the activities chosen.

earliest start first: 1 joblooks in order: A B C DABCD0123456789
earliest finish first: 3 jobslooks in order: B C A DABCD0123456789
The watch page's first example, A to D, hours 0 to 9 below. Earliest start first takes A alone. Earliest finish first takes B, C and D.
in orderhoursfree fromdoes
B1 to 2-choose
C3 to 42choose
A0 to 64rule out
D5 to 74choose
Earliest finish first, row by row. A dash means nothing is chosen yet. A starts at 0, before the room is free at 4, so it is ruled out.
Starting earliest is not best: 6 moments of its 6 steps, the steps between them left for the watch page
  1. step 1 of 6

    012345678BCADBCAAAAAADD

    Line the 4 activities up by the hour each ends, earliest first: B, C, A and D.

    what it remembers to know where it is
    room free from
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  2. step 2 of 6

    012345678BCADBCAAAAAADD

    B runs from 1 to 2 and ends earliest. Nothing is chosen yet, so choose B. The room is free again from 2.

    what it remembers to know where it is
    room free from
    2

    watch from here

  3. step 3 of 6

    012345678BCADBCAAAAAADD

    C runs from 3 to 4. The last one chosen, B, ends at 2, so C fits after it. Choose C.

    what it remembers to know where it is
    room free from
    4

    watch from here

  4. step 4 of 6

    012345678BCADBCAAAAAADD

    A runs from 0 to 6, but starts before C, the last one chosen, ends at 4, so they clash. Rule A out.

    what it remembers to know where it is
    room free from
    4

    watch from here

  5. step 5 of 6

    012345678BCADBCAAAAAADD

    D runs from 5 to 7. The last one chosen, C, ends at 4, so D fits after it. Choose D.

    what it remembers to know where it is
    room free from
    7

    watch from here

  6. step 6 of 6

    012345678BCADBCAAAAAADD

    Done: B, C and D fit, 3 activities with no two at once, the most there can be.

    what it remembers to know where it is
    room free from
    7

    watch from here

the steps, in plain words
  1. line the activities up by the hour each ends, earliest firstPython lines 9 and 10
  2. take each in that orderPython line 11
  3. it starts once the last one chosen has ended, or nothing is chosen yet, so choose itPython lines 14 and 15
  4. otherwise it clashes with the last one chosen: rule it outPython lines 12 and 13
  5. the activities chosen are as many as fitPython line 16
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

def activity_selection(activities):
    """Fit the most activities into one room, no two at once.

    activities is a list of (start, end) pairs of whole hours, each ending
    after it starts. Returns the activities chosen, in the order chosen.
    """
    chosen = []
    free = None  # the hour the room is free again from; nothing chosen yet
    # line them up by the hour each ends, earliest first; equal ends by start
    in_order = sorted(activities, key=lambda a: (a[1], a[0]))
    for start, end in in_order:  # take each in that order
        if free is not None and start < free:  # it starts before the last one chosen ends
            continue  # so they clash: rule it out
        chosen.append((start, end))  # choose it
        free = end  # the room is free again from its end
    return chosen  # as many as fit

how it scales

The plot counts the sort's comparisons on nn activities, each an hour long, back to back, in two orders. Latest end first is the fewest any order costs, and the dearest order the most. Measured from 10 to 100,000.

Each mark across or up is ten times the one before. Both lines climb a little over one mark up for each mark across. The dearest order makes 589 at 100 activities and 8,985 at 1,000, about 15 times. The plot's note reads it further out, from a million to ten million activities: about 12 times. The extra over ten times comes from the log in n log⁡2 nn \,\log_2\, n, which section 4 derives.

comparisons to line them up, ten times more at each mark up

a secondslope 1.1102104106108101102103104105106107a secondslope 1.1101102103104105106107108109101102103104105106107a secondslope 1.1101102103104105106107108109101102103104105106107

nn, how many activities there are, ten times more at each mark to the right

  • the dearest order, each an hour longsolid where measured by running it; dashed where its formula carries it on to ten millionslope 1.1: ten times n, 12 times the work
  • latest end first, each an hour longsolid where measured by running it; dashed where its formula carries it on to ten million
how long the dearest order takes, at a billion comparisons a second
nncomparisons to line them uptime
1,0008,985about 9 microseconds
100,0001,592,993about 1.6 milliseconds
10,000,000226,648,193about 227 milliseconds

The comparisons to line them up are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

"""Count activity selection's comparisons yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each size n it lines up n activities,
each an hour long, back to back, in two orders: latest end first, the fewest
comparisons any order costs, and the dearest order, the most. It prints the
comparisons the sort makes for each, by count below, the watch page's merge
in place of Python's own sorted. The counts are the same on any computer;
only the time differs.
"""


def activity_selection(activities):
    """Fit the most activities into one room, no two at once.

    activities is a list of (start, end) pairs of whole hours, each ending
    after it starts. Returns the activities chosen, in the order chosen.
    """
    chosen = []
    free = None  # the hour the room is free again from; nothing chosen yet
    # line them up by the hour each ends, earliest first; equal ends by start
    in_order = sorted(activities, key=lambda a: (a[1], a[0]))
    for start, end in in_order:  # take each in that order
        if free is not None and start < free:  # it starts before the last one chosen ends
            continue  # so they clash: rule it out
        chosen.append((start, end))  # choose it
        free = end  # the room is free again from its end
    return chosen  # as many as fit


def count(activities):
    """How many comparisons the watch page's sort makes: runs of 1, 2, 4
    and on, merged in neighbouring pairs, comparing their front activities
    by end, and by start when two end at the same hour."""
    runs = [[(end, start)] for start, end in activities]
    compared = 0
    while len(runs) > 1:
        merged = []
        for k in range(0, len(runs) - 1, 2):
            left, right = runs[k], runs[k + 1]
            run = []
            i = j = 0
            while i < len(left) and j < len(right):
                compared += 1
                if right[j] < left[i]:
                    run.append(right[j])
                    j += 1
                else:
                    run.append(left[i])
                    i += 1
            merged.append(run + left[i:] + right[j:])
        if len(runs) % 2 == 1:
            merged.append(runs[-1])
        runs = merged
    return compared


def cheapest(n):
    """n activities an hour long, back to back, typed latest end first."""
    return [(n - 1 - k, n - k) for k in range(n)]


def dearest(n):
    """n activities an hour long, back to back, their ends in the dearest
    order: in every merge, the two latest ends sit in different runs."""
    order = [0] * n

    def deal(at, ends):
        if len(ends) == 1:
            order[at] = ends[0]
            return
        split = 1
        while split * 2 < len(ends):  # the largest power of 2 below the run's length
            split *= 2
        left, right = [], []
        for i, end in enumerate(reversed(ends)):  # from the latest end down
            if i % 2 == 0 and len(right) < len(ends) - split:
                right.insert(0, end)
            else:
                left.insert(0, end)
        deal(at, left)
        deal(at + split, right)

    deal(0, list(range(1, n + 1)))
    return [(end - 1, end) for end in order]


if __name__ == "__main__":
    print(f"{'n':>7} {'latest end first':>17} {'dearest':>10}")
    for n in (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000, 20_000, 50_000, 100_000):
        print(f"{n:>7} {count(cheapest(n)):>17} {count(dearest(n)):>10}")

best, worst and average

Here best and worst are orders: the same activities, typed in a different order. Which runs the sort merges depends only on nn; where each merge stops, when one run is used up, depends on the order typed. So the order alone moves the comparisons. The checks never move: n−1n - 1 on every list. No average is worked out.

A case is one order of the activities. A bound says how fast that order's cost grows as activities are added.

The counts are in the grid below. A count is often made of pieces that grow at different speeds, and the fastest-growing piece swamps the rest. In the dearest order at 1,000 activities, n⌈log⁡2 n⌉n \lceil \log_2\, n \rceil is 10,000, less 16 waiting and 999 for the merges: 8,985. The 10,000 is most of it. So how a cost grows is what tells one method from another, and the bounds keep just that.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
bestlatest end first, each an hour longworstthe dearest order, each an hour long
comparisons to line them upb1+b2+b4+…b_1 + b_2 + b_4 + \dots, the right runsn⌈log⁡2 n⌉−w−(n−1)n \lceil \log_2\, n \rceil - w - (n - 1)
activities checkedn−1n - 1n−1n - 1
how the comparisons to line them up grow in each case
tight, Θ\ThetaΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)
ceiling, OOO(n log⁡2 n)O(n \,\log_2\, n)O(n log⁡2 n)O(n \,\log_2\, n)
floor, Ω\OmegaΩ(n log⁡2 n)\Omega(n \,\log_2\, n)Ω(n log⁡2 n)\Omega(n \,\log_2\, n)

extra memory: A second list of the activities for the sort, and the activities chosen.

Extra memory is the room it needs on top of the input itself, while it runs.

typedendscomparisonschecks
latest end first5, 4, 3, 2, 154
in end order1, 2, 3, 4, 584
the dearest order1, 3, 2, 4, 594
Five activities, each an hour long, written by the hour each ends. The comparisons move with the order typed, from 5 to 9. The checks stay at 4.
earliest finish first: 1 joblooks in order: A B CABC0123456789
The watch page's third example. All three overlap, so earliest finish first takes A alone. 3 comparisons and 2 checks.
earliest finish first: 3 jobslooks in order: A B CABC0123456789
Three that touch end to end, their ends in the same order. Earliest finish first takes all three. Again 3 comparisons and 2 checks.

where the formula comes from

Questions 1 and 2 count the comparisons, the plot's two lines. Question 3 counts the checks, and question 4 shows why the activities chosen are the most.

Question 1: how many comparisons, FF, does the sort make on nn activities typed latest end first, from 2 up?
  1. the move: how the sort goes

    the line:
    runs of 1,2,4,…merged in pairs\begin{gathered} \text{runs of } 1, 2, 4, \dots \\ \text{merged in pairs} \end{gathered}
    the row: 5, 4, 3, 2, 111111start221round 141round 25round 32a run, its length insideno partner, carried downthe first runall in one runa merge in round 2, its numbers45232345goes straight in, the other run used up
    5 numbers stand for 5 activities' ends, latest first. Round 2's merge, 4, 5 with 2, 3, compares 2 with 4, then 3 with 4. Then the right run is used up, and 4 and 5 follow with no comparison.
    roundrun lengthmergescomparisons
    1122
    2212
    3411
    all45
    Five activities, latest end first. In rounds 1 and 2 the last run waits.

    why it is allowed: The watch page's sort is merge sort, from the bottom up. Each activity starts as a run of 1. Each round merges neighbouring runs, comparing their front activities and taking the one that ends first. A last run with no partner waits. Every run is 1, 2, 4 and on long, except perhaps a round's last, so a right run is never the longer. Which runs meet depends only on nn, never on the order.

  2. the move: a merge's least

    the line:
    a merge compares at leastits right run’s length\begin{gathered} \text{a merge compares at least} \\ \text{its right run's length} \end{gathered}

    why it is allowed: A merge stops when one run is used up, and each activity of that run needed one comparison to leave it. By line 1, the right run is never the longer. So whichever run is used up holds at least the right run's length. For 4, 5 with 2, 3, at least 2 comparisons.

  3. the move: latest end first, the right run is used up first

    the line:
    F=b1+b2+b4+…F = b_1 + b_2 + b_4 + \dots
    run lengthright runscomparisons
    15 of 15
    22 of 24
    41 of 44
    81 of 22
    all15
    Ten activities, latest end first. At run length 2 the last run waits, and at 4 the last 2 activities wait. At 8 the right run holds only those 2.

    why it is allowed: Latest end first, each right run's activities end before the left run's beside it. So the right run is used up first, one comparison each, the least line 2 allows. b1b_1 adds up the right runs in the round of runs of 1, b2b_2 of runs of 2, and so on. For 5, 2 + 2 + 1.

  4. the move: a ceiling

    the line:
    F≤n2⌈log⁡2 n⌉F \le \frac{n}{2} \lceil \log_2\, n \rceil
    numberlog× 2+ 11021428316452.32103.32
    Top, numbers, each double the last; bottom, their logs, each 1 more. 5 lies between 4 and 8, so its log, about 2.3, rounds up to 3. 10 lies between 8 and 16, so its log, about 3.3, rounds up to 4.

    why it is allowed: In a pair the right run is never the longer, so a round's right runs hold at most half the activities, n2\frac{n}{2}. Run lengths double until one run holds all nn, so there are ⌈log⁡2 n⌉\lceil \log_2\, n \rceil rounds. Multiply the two. For 5, half of 5 times 3 rounds is 7.5, and FF is 5.

  5. the move: a simpler ceiling

    the line:
    F≤n log⁡2 nF \le n \,\log_2\, n

    why it is allowed: Rounding up adds less than 1, and from 2 up 1 is at most log⁡2 n\log_2\, n. So ⌈log⁡2 n⌉\lceil \log_2\, n \rceil is at most twice log⁡2 n\log_2\, n, and n2\frac{n}{2} times twice log⁡2 n\log_2\, n is n log⁡2 nn \,\log_2\, n. For 5, FF is 5, at most 11.6.

  6. the move: read the bound

    the line:
    F∈O(n log⁡2 n)F \in O(n \,\log_2\, n)

    why it is allowed: By line 5, with the fixed multiple 1.

  7. the move: a floor

    the line:
    F≥n4⌊log⁡2 n⌋F \ge \frac{n}{4} \lfloor \log_2\, n \rfloor
    run lengthfull pairs holdtheir right runsa quarter of 5
    1421.25
    2421.25
    Five activities. In each round with a full pair, the full pairs hold 4 of the 5, at least half, and their right runs 2, at least a quarter. 2 such rounds, so at least 2.5.

    why it is allowed: Take a round whose runs are rr long, with 2r2r at most nn, so at least one full pair of runs fits. What is left over is shorter than a pair, so the full pairs hold at least half the activities, and their right runs at least a quarter, n4\frac{n}{4}. Such rounds have rr as 1, 2, 4 and on, while 2r2r is at most nn, so there are ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor of them. By line 3, FF adds up every round's right runs, so multiply the two. For 5, rounds of 1 and 2, so at least 2.5.

  8. the move: the rounded log against the exact one

    the line:
     log⁡2 n is below j+1,at most 2j\begin{gathered} \,\log_2\, n \text{ is below } j + 1, \\ \text{at most } 2j \end{gathered}

    why it is allowed: Call line 7's rounded-down log jj. Rounding down took off less than 1, so log⁡2 n\log_2\, n is below j+1j + 1. From 2 up jj is at least 1, so j+1j + 1 is at most 2j2j. For 5, jj is 2, and the log of 5, about 2.3, is below 3, at most 4.

  9. the move: drop the rounding

    the line:
    F≥n log⁡2 n8F \ge \frac{n \,\log_2\, n}{8}

    why it is allowed: By line 8, jj is at least half of log⁡2 n\log_2\, n. Put that into line 7. For 5, FF is 5, at least 1.45.

  10. the move: read the bound

    the line:
    F∈Ω(n log⁡2 n)F \in \Omega(n \,\log_2\, n)

    why it is allowed: By line 9, with the fixed multiple an eighth.

  11. the move: both together

    the line:
    F∈Θ(n log⁡2 n)F \in \Theta(n \,\log_2\, n)

    why it is allowed: Lines 6 and 10 bound FF by the same growth.

try it with a small nn: at n=5n = 5, line 3 gives F=5F = 5, which you can work out by hand

Question 2: how many comparisons, MM, does the sort make on nn activities in the dearest order, from 2 up?
  1. the move: a merge's most

    the line:
    runs of p and q activitiescompare at most p+q−1\begin{gathered} \text{runs of } p \text{ and } q \text{ activities} \\ \text{compare at most } p + q - 1 \end{gathered}

    why it is allowed: Each comparison sends one activity into the new run. When one run is used up, the other still holds at least one activity, which follows with no comparison.

  2. the move: the dearest order

    the line:
    every merge’s two latestends sit in different runs\begin{gathered} \text{every merge's two latest} \\ \text{ends sit in different runs} \end{gathered}
    run of endsleft run getsright run gets
    1, 2, 3, 4, 51, 2, 3, 45
    1, 2, 3, 41, 32, 4
    1, 313
    2, 424
    Dealing 5 ends. 5 goes right, and a right run of 1 is full, so 1 to 4 go left. Then 4 goes right, 3 left, 2 right and 1 left. Each left run is typed before its right run, so the order is 1, 3, 2, 4, 5.

    why it is allowed: By question 1's line 1, a run of mm activities is merged from two runs. The left run holds the largest power of 2 below mm, and the right run the rest. Deal its ends out from the latest down, one to the right run and one to the left in turn, until the right run is full. The rest go left. Then deal each run the same way. The run without the latest end holds the second latest, its own last, and is used up when that goes in. So only the latest is left, and the merge makes the p+q−1p + q - 1 of line 1.

  3. the move: each merge, one less than it holds

    the line:
    comparisons: activities merged,less one for each merge\begin{gathered} \text{comparisons: activities merged,} \\ \text{less one for each merge} \end{gathered}
    mergemergedcomparisons
    1 with 321
    2 with 421
    1, 3 with 2, 443
    1, 2, 3, 4 with 554
    all139
    The dearest order of 5 ends: 1, 3, 2, 4, 5. The watch page's second example has its ends in this order. 13 merged, 4 merges, 9 comparisons.

    why it is allowed: By line 2, each merge compares one less than it holds. Add that up over every merge.

  4. the move: the activities merged

    the line:
    activities merged:n⌈log⁡2 n⌉−w\begin{gathered} \text{activities merged:} \\ n \lceil \log_2\, n \rceil - w \end{gathered}

    why it is allowed: Each of the ⌈log⁡2 n⌉\lceil \log_2\, n \rceil rounds, as in question 1's line 4, merges every activity except a run that waits. ww adds up the activities that wait. For 5, 15 less 2, which is 13.

  5. the move: the merges

    the line:
    merges: n−1\text{merges: } n - 1

    why it is allowed: Each merge makes one run fewer, from nn runs to 1. For 5, 4.

  6. the move: put them together

    the line:
    M=n⌈log⁡2 n⌉−w−(n−1)M = n \lceil \log_2\, n \rceil - w - (n - 1)

    why it is allowed: Lines 3, 4 and 5 together. For 5, 13 less 4, which is 9.

  7. the move: a ceiling

    the line:
    M≤n⌈log⁡2 n⌉M \le n \lceil \log_2\, n \rceil

    why it is allowed: By line 6, dropping the ww and the n−1n - 1 it takes away, as neither is below 0. For 5, 9 is at most 15.

  8. the move: a simpler ceiling

    the line:
    M≤2n log⁡2 nM \le 2n \,\log_2\, n

    why it is allowed: As in question 1's line 5, ⌈log⁡2 n⌉\lceil \log_2\, n \rceil is at most twice log⁡2 n\log_2\, n. For 5, at most 23.2.

  9. the move: read the bound

    the line:
    M∈O(n log⁡2 n)M \in O(n \,\log_2\, n)

    why it is allowed: By line 8, with the fixed multiple 2.

  10. the move: a floor

    the line:
    M≥n4⌊log⁡2 n⌋M \ge \frac{n}{4} \lfloor \log_2\, n \rfloor

    why it is allowed: By question 1's line 2, every merge compares at least its right run, in any order. So MM is at least question 1's FF, and question 1's line 7 gives FF this floor. For 5, 9 is at least 2.5.

  11. the move: drop the rounding

    the line:
    M≥n log⁡2 n8M \ge \frac{n \,\log_2\, n}{8}

    why it is allowed: As in question 1's lines 8 and 9. For 5, at least 1.45.

  12. the move: read the bound

    the line:
    M∈Ω(n log⁡2 n)M \in \Omega(n \,\log_2\, n)

    why it is allowed: By line 11, with the fixed multiple an eighth.

  13. the move: both together

    the line:
    M∈Θ(n log⁡2 n)M \in \Theta(n \,\log_2\, n)

    why it is allowed: Lines 9 and 12 bound MM by the same growth.

try it with a small nn: at n=5n = 5, line 6 gives M=9M = 9, which you can work out by hand

Question 3: how many checks, KK, does the method make on nn activities, from 2 up?
  1. the move: one check each, after the first

    the line:
    K=n−1K = n - 1
    in orderhoursfree fromchecks so fardoes
    A0 to 3-0choose
    C3 to 531choose
    B2 to 752rule out
    D5 to 853choose
    E6 to 984rule out
    Section 5's five activities, in order of ends. A is chosen with no check. Each of the other 4 is checked once, chosen or ruled out.

    why it is allowed: The first activity in order is chosen with no check, as nothing is chosen yet. Each other is checked once, against the hour the room is free from. In any order. For 5, 4.

  2. the move: a ceiling

    the line:
    K≤nK \le n

    why it is allowed: By line 1, as n−1n - 1 is less than nn.

  3. the move: read the bound

    the line:
    K∈O(n)K \in O(n)

    why it is allowed: By line 2, with the fixed multiple 1.

  4. the move: a floor

    the line:
    K≥n2K \ge \frac{n}{2}

    why it is allowed: From 2 up, 1 is at most half of nn, so n−1n - 1 is at least half of nn. For 5, 4 is at least 2.5.

  5. the move: read the bound

    the line:
    K∈Ω(n)K \in \Omega(n)

    why it is allowed: By line 4, with the fixed multiple a half.

  6. the move: both together

    the line:
    K∈Θ(n)K \in \Theta(n)

    why it is allowed: Lines 3 and 5 bound KK by the same growth.

  7. the move: the sort grows faster

    the line:
    comparisons over checks:at least log⁡2 n8\begin{gathered} \text{comparisons over checks:} \\ \text{at least } \frac{\log_2\, n}{8} \end{gathered}

    why it is allowed: By question 1's lines 2, 3 and 9, any order makes at least n log⁡2 n8\frac{n \,\log_2\, n}{8} comparisons, and by line 2 the checks are at most nn. So the comparisons are at least log⁡2 n8\frac{\log_2\, n}{8} times the checks, a number that grows without end. It is 1 or more from 256 on, as the log of 256 is 8. At 1,000 activities, 999 checks against 4,932 to 8,985 comparisons. At 100,000, 99,999 against 815,024 to 1,592,993.

try it with a small nn: at n=5n = 5, line 1 gives K=4K = 4, which you can work out by hand

Question 4: a best list holds kk activities. Swap its activity that ends first for this method's first. How many activities, SS, does it hold now, and why is the method's list a best list?
  1. the move: one out, one in

    the line:
    S=(k−1)+1S = (k - 1) + 1
    a best list: 3 jobsABCDE0123456789
    after swap 1: 3 jobsABCDE0123456789
    after swap 2: 3 jobsABCDE0123456789
    Five activities, hours 0 to 9 below. A best list, A, C and E. Swap 1 puts B, the method's first, in for A. Swap 2 puts D, its second, in for C. No swap makes a clash.

    why it is allowed: The plan is to turn a best list into this method's list, one swap at a time, never losing an activity. In the picture, A goes out and B comes in. The page on greedy choices proves this under line 2, on five jobs of its own. It calls activities jobs, a list with no clash a day, and this method earliest finish.

  2. the move: add them up

    the line:
    S=kS = k
    where does this come from?
    question 1 of the page greedy choices, and when they failA best day holds kk jobs. Swap its job that ends first for earliest finish's first job. How many jobs, SS, does it hold now, and does any clash?
    1. the move: one out, one in

      the line:
      S=(k−1)+1S = (k - 1) + 1
      a best day: 2 jobsABCDE0123456789
      after swap 1: 2 jobsABCDE0123456789
      after swap 2: 2 jobsABCDE0123456789
      A best day of the jobs at the top, C and E. Swap 1 puts B, earliest finish's first job, in for C. Swap 2 puts D, its second, in for E. No swap makes a clash.

      why it is allowed: The plan is to turn a best day into earliest finish's day, one swap at a time, never losing a job. One job goes out and one comes in. On the day at the top, C goes out and B comes in.

    2. the move: add them up

      the line:
      S=kS = k

      why it is allowed: One out and one in leaves kk. B and E are 2 jobs, as C and E were.

    3. the move: nothing clashes

      the line:
      the swapped day:no clash\begin{gathered} \text{the swapped day:} \\ \text{no clash} \end{gathered}
      a best day: 2 jobsABCDE0123456789
      after swap 1: 2 jobsABCDE0123456789
      Swap 1, B in for C. B and E fit.

      why it is allowed: B ends at 2, before C ends at 3. E starts at 3, so no earlier than B ends, and B and E fit. In general, the job put in ends first of all, so no later than the job taken out. Every other job of the best day ends no earlier than the one taken out, so it cannot sit wholly before it. As they do not clash, it starts no earlier than that job ends, so no earlier than the new one ends.

    4. the move: swap again

      the line:
      swap job 2, then 3,and so on\begin{gathered} \text{swap job 2, then 3,} \\ \text{and so on} \end{gathered}
      after swap 1: 2 jobsABCDE0123456789
      after swap 2: 2 jobsABCDE0123456789
      Swap 2, D in for E. B and D fit.

      why it is allowed: Both days now start with B, and only jobs starting at 2 or later can sit beside it. Each time, earliest finish takes the job ending first of those starting no earlier than its last job ends. Here that is D, ending at 4. E, the best day's second job, starts at 3, so it is one of them, and ends at 5. So D ends no later than E. D fits beside B, as it starts no earlier than B ends. Any later job of the best day starts no earlier than E ends, as in line 3, so no earlier than D ends. Each next job swaps the same way.

    5. the move: none left over

      the line:
      no best day beatsearliest finish\begin{gathered} \text{no best day beats} \\ \text{earliest finish} \end{gathered}

      why it is allowed: Earliest finish's jobs are a day too, so a best day holds at least as many, and the swaps never run out. Swap until every job of earliest finish is in. Any job left over in the best day ends no earlier than the last one swapped in, so, as in line 3, it starts no earlier than that job ends. Then earliest finish would have taken it too. So the best day has no more. At the top, after the swaps the day is B and D, and no job starts at 4 or later.

    the whole page: greedy choices, and when they fail

    why it is allowed: One out and one in leaves kk.

  3. the move: nothing clashes

    the line:
    the swapped list:no clash\begin{gathered} \text{the swapped list:} \\ \text{no clash} \end{gathered}

    why it is allowed: By line 3 of the proof under line 2, the activity put in ends first of all, so the rest of the best list still fits after it. In line 1's picture, B ends at 2, before A ends at 3, so C, starting at 3, still fits.

  4. the move: none left over

    the line:
    no best list holdsmore than the method’s\begin{gathered} \text{no best list holds} \\ \text{more than the method's} \end{gathered}

    why it is allowed: The method's list has no clash either, so a best list holds at least as many, and the swaps never run out. By lines 4 and 5 of the proof, an activity left over would start once the last one swapped in ends. Then the method would have chosen it too, yet it is not in the method's list. So none is left over, and the method's list is a best list. Here B, D and E, 3.

try it with a small kk: at k=3k = 3, line 1 gives S=3S = 3, which you can work out by hand

count it yourself

Five activities: A from 0 to 3, B from 2 to 7, C from 3 to 5, D from 5 to 8 and E from 6 to 9. Their ends, 3, 7, 5, 8, 9, come in the dearest order, the pattern of 1, 3, 2, 4, 5. The sort makes all 9 comparisons before step 1, so they show together there. Then each activity after the first is checked once. The last columns are running totals.

0-3, 2-7, 3-5, 5-8, 6-9, every step written down
stepwhat happenscomparisons to line them upactivities checked
1Line the 5 activities up by the hour each ends, earliest first: A, C, B, D and E.90
2A runs from 0 to 3 and ends earliest. Nothing is chosen yet, so choose A. The room is free again from 3.90
3C runs from 3 to 5. The last one chosen, A, ends at 3, so C fits after it. Choose C.91
4B runs from 2 to 7, but starts before C, the last one chosen, ends at 5, so they clash. Rule B out.92
5D runs from 5 to 8. The last one chosen, C, ends at 5, so D fits after it. Choose D.93
6E runs from 6 to 9, but starts before D, the last one chosen, ends at 8, so they clash. Rule E out.94
7Done: A, C and D fit, 3 activities with no two at once, the most there can be.94

In all, 9 comparisons to line them up. The formula from section 4, n⌈log⁡2 n⌉−w−(n−1)n \lceil \log_2\, n \rceil - w - (n - 1), gives M=9M = 9 at n=5n = 5: the same.

where you meet it

The books' courier fills a day this way. Drawn as points joined by lines, the problem has fast methods of its own. Textbooks start their chapters on greedy methods with it.

  • The courier's day

    The books give a courier eight delivery jobs, each in a fixed window, each paying the same. Earliest finish first takes six. Earliest start first takes four. Checking all 256 sets of the eight finds no seven that fit.

    source: the books' volume three, chapter 30

  • Graphs of activities

    Draw each activity as a point, and join two points when the activities clash. The most that fit is then the largest set of points with no two joined. In 1972, Fănică Gavril gave fast methods for this on chordal graphs, a family of such drawings that holds every one made from activities.

    source: F. Gavril, SIAM Journal on Computing 1(2), 1972, pages 180 to 187, Algorithms for minimum coloring, maximum clique, minimum covering by cliques, and maximum independent set of a chordal graph (opens in a new tab)

  • Where textbooks start

    Kleinberg and Tardos's textbook opens its chapter on greedy methods with this problem, calling it interval scheduling. It proves earliest finish first right by showing the method never falls behind a best list. Cormen and others' textbook opens its greedy chapter with it too, as activity selection.

    source: J. Kleinberg and É. Tardos, Algorithm Design, Addison-Wesley, 2006, section 4.1, and T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, 3rd edition, MIT Press, 2009, section 16.1

what is used instead

When activities pay different amounts, earliest finish first can lose. A table of the best pay for the first few activities, filled one at a time, finds the most pay (Kleinberg and Tardos, sections 6.1 and 6.2). With several rooms and every activity to place, take them by start and open a new room only when every room is busy (section 4.1).

how it compares

Other rules look as sensible, and each loses on some list. Trying every set of activities always finds the most, but each activity added doubles the sets: 10 activities have 1,024.

ruletakes nextalways the most
earliest finish firstthe one ending first that fitsyes
earliest start firstthe one starting first that fitsno: 1 for 3 in section 1
shortest firstthe shortest that fitsno: 1 for 2 below
every settries every setyes
Four ways to fill one room. Only earliest finish first and trying every set always find the most.
shortest first: 1 joblooks in order: B A CABC0123456789
earliest finish first: 2 jobslooks in order: A B CABC0123456789
Three activities. Shortest first takes B, 3 hours, which clashes with A and C. Earliest finish first takes A and C.
nearliest finish first: comparisons and checksevery set: sets
10361,024
20921,048,576
402241,099,511,627,776
Earliest finish first counted in the dearest order, each set tried counted once. 20 more activities add 132 steps to earliest finish first and multiply the sets about a million times.