Drill

ProblemsPython › patterns

The busiest stretch of the day

mediumpatternsSliding windowArraysPython

A traffic chart holds one count per minute. The headline figure is the busiest run of a fixed number of consecutive minutes.

busiest_stretch(per_minute: list<int>, run_length: int) → int

Solve it in the editor →

Where you start

def busiest_stretch(per_minute: list[int], run_length: int) -> int:
    

Worked examples

CallResult
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

The same problem in another language

More patterns problems in Python