The handoff day has to fit two windows at once
The handoff day k is the first person's last day. It has to pass three checks:
- Each person works at least one day, so
start <= k <= end - 1. - The first is free every day through
k, sok <= reach_a. - The second is free from
k + 1on, sok >= begins_b - 1.
So k lies in two closed intervals at once, (start, end - 1) and (begins_b - 1, reach_a). Take the later start and the earlier end. The pair works when that window isn't empty:
# a and b are (reach, begins) pairs
def handoff_days(a, b, start, end):
reach_a, _ = a
_, begins_b = b
first, last = max(start, begins_b - 1), min(end - 1, reach_a)
return (first, last) if first <= last else None
# from the table
RB = {"ana": (3, 6), "bo": (0, 3), "cy": (4, 8), "fay": (1, 5)}
for first, second in [("cy", "bo"), ("cy", "fay"), ("ana", "fay")]:
print(first, second, handoff_days(RB[first], RB[second], 1, 7))
cy bo (2, 4)
cy fay (4, 4)
ana fay None
Here are those three pairs on the grid. A k marks each day that can be the first person's last day:
cy, then bo cy, then fay ana, then fay cy can hand to bo on any of days 2 to 4, and to fay only after day 4. ana and fay have no day 4 between them, so they fail.
The closed overlap test won't do here, because (begins_b - 1, reach_a) is often empty. For ana then fay it's (4, 3): nobody covers day 4, and the closed test still says it overlaps (1, 6).
Over every ordered pair from the table, the days that work:
| First | Second | Handoff days |
|---|---|---|
| ana | bo | 2 to 3 |
| ana | dev | 1 to 3 |
| cy | bo | 2 to 4 |
| cy | dev | 1 to 4 |
| cy | fay | 4 |
| fay | dev | 1 |
| eli | ana, bo, dev or fay | 5 to 6, 2 to 6, 1 to 6, 4 to 6 |
| ana, cy or fay | eli | 1 to 3, 1 to 4, 1 |
It agreed with the slow day-by-day check on every pair here and on 500 random cases. The last two rows involve eli, who can take the whole week alone. Whether a pair with someone like that counts is a rule of the problem, so read it or ask.
In the editor, handoff_days(a, b, start, end) is the window test above with one bound changed. It lets eli's last day be day 7, which leaves ana no day at all. Fix the window.