Among the shifts that start by the first uncovered day, take the one that reaches farthest
Some shift has to cover day 1. Among the shifts that do, take the one that reaches farthest, (1, 5).
Why is that safe? Whatever shift the best answer used for day 1, swap it for (1, 5). Both start by day 1, and (1, 5) ends no earlier. So it covers every day that shift covered from day 1 on. The answer still covers the rotation with the same count, so the swap never hurts.
Now the first uncovered day is 6, and the same argument applies. Among the shifts that start on day 6 or earlier, take the one that reaches farthest. Repeat until day 14 is covered. If no shift that starts by the first uncovered day reaches past what's covered, that day has no shift, and the answer is -1.
def fewest_shifts(shifts, start, end):
# by start day
shifts = sorted(shifts)
# days start..covered are covered
count, covered, i = 0, start - 1, 0
while covered < end:
reach = covered
# starts by the first uncovered day
while i < len(shifts) and shifts[i][0] <= covered + 1:
reach = max(reach, shifts[i][1])
i += 1
# nothing covers day covered + 1
if reach == covered:
return -1
count, covered = count + 1, reach
return count
print(fewest_shifts(SHIFTS, 1, 14))
3
Trace it the way you'd narrate it:
| Round | First uncovered day | Shifts that start by then | Farthest reach | Covered through |
|---|---|---|---|---|
| 1 | 1 | (1, 3), (1, 5) | 5 | 5 |
| 2 | 6 | (2, 8), (4, 6), (6, 12) | 12 | 12 |
| 3 | 13 | (7, 10), (9, 14), (11, 14), (13, 14) | 14 | 14 |
Three shifts, (1, 5), (6, 12) and (9, 14). Here they are with the first uncovered day of each round:
The lines mark the first uncovered day of each round: 1, 6 and 13.
Each shift is looked at once, because i only moves forward. A shift that started early enough for one round started early enough for every later one. So the next round only needs the shifts after it.
In the editor, chosen(shifts, start, end) is fewest_shifts changed to return the shifts it picks. Write the inner loop, which keeps in best the shift that reaches farthest.