The busiest stretch of the day
A traffic chart holds one count per minute. The headline figure is the busiest run of a fixed number of consecutive minutes.
- The window is a run of exactly `runLength` consecutive minutes.
- If the day is shorter than the window, there is no such run: return 0.
- A window size of zero or less also returns 0.
busiest_stretch(per_minute: list<int>, run_length: int) → int
Where you start
def busiest_stretch(per_minute: list[int], run_length: int) -> int:
Worked examples
| Call | Result |
|---|---|
busiest_stretch([1, 4, 2, 10, 2, 3, 1, 0, 20], 4) | 24 |
busiest_stretch([2, 3], 3) | 0 |
busiest_stretch([5, 5, 5], 1) | 5 |
busiest_stretch([1, 2, 3], 3) | 6 |
Hint
Total the first window, then slide: add the minute coming in and subtract the one going out. Re-adding the whole window each step is the slow way.
Reference solution in Python
def busiest_stretch(per_minute: list[int], run_length: int) -> int:
if run_length <= 0 or len(per_minute) < run_length:
return 0
window = sum(per_minute[:run_length])
best = window
for i in range(run_length, len(per_minute)):
window += per_minute[i] - per_minute[i - run_length]
if window > best:
best = window
return best