Code

Side Quest: Grow and Shrink

In The Leaky Window the window was always k items wide. Some questions don't give you a k. For example: "What's the longest run of days Pip can sail on 6 units of fuel?"

A window that changes size

A variable-size window grows on the right, one item at a time. Whenever it costs too much, it shrinks from the left until it fits again:

left = 0
total = 0
best = 0
for right in range(len(costs)):
    total += costs[right]        # grow: add the new day
    while total > budget:        # too much? shrink
        total -= costs[left]
        left += 1
    best = max(best, right - left + 1)

The window is costs[left:right + 1], so its length is right - left + 1. It can even shrink to nothing (length 0) when one day alone is over budget.

Why it's fast

There's a loop inside a loop, but right moves forward n times and left only ever moves forward too, at most n times. So the whole thing takes O(n) steps, not O(n²).

It only works because costs are never negative. Adding a day can only raise the total, and dropping one can only lower it. With negative numbers, shrinking might make things worse, and you'd need a different method.

Assignment

costs is a list of whole numbers, 0 or more. budget is 0 or more.

  1. longest_run(costs, budget): return the length of the longest run of consecutive days whose total is at most budget. Return 0 if no single day fits.
  2. first_longest(costs, budget): return that run itself, as a slice of costs. If several runs tie, return the one that starts first. Return [] if none fits.
  3. Use one grow-and-shrink window in each. Don't try every start and end.