15/42
Part 4 of 8 · The sweepLearn and do

On half-open times, an end goes before a start at the same instant

At time 4 in the figure, two reservations end and one starts. Here are all the events, in the order the sort puts them:

TimeEventOpen after it
1start of (1, 4)1
2start of (2, 5)2
3start of (3, 4)3
4end of (1, 4)2
4end of (3, 4)1
4start of (4, 7)2
5end of (2, 5)1
5start of (5, 8)2
7end of (4, 7)1
8end of (5, 8)0

Half-open says the ones that end at 4 are already over when the one at 4 begins. So the ends must go first. The events are tuples, and tuples sort field by field. So at one time, (4, -1) comes before (4, 1) with no extra code.

Process the starts first instead, as a key of (time, -change) does, and see what happens:

def peak(events, key=None):
    now = most = 0
    for _, change in sorted(events, key=key):
        now += change
        most = max(most, now)
    return most


events = [(s, 1) for s, e in R] + [(e, -1) for s, e in R]
# ends first
print(peak(events))
# starts first
print(peak(events, key=lambda e: (e[0], -e[1])))
3
4

With starts first, the count climbs to 4 at time 4 before the ends come off. The function reports 4 machines where 3 are enough.

In the editor, write busiest(reservations): the sweep, returning the most reservations open at once and the earliest time that many are open, with ends before starts at one instant.