25/32
Part 6 of 6 · Follow-upsLearn and do

What's the largest value in every window?

A max can't be updated when an entry leaves. If the max is the one leaving, you don't know the next largest.

Keep a deque of indexes whose values go down from front to back. A new value first pops every smaller or equal value off the back, since those can never be the max again while it's in the window. The front is then the max, and it leaves when it falls out of the window. Say the values are requests per second:

from collections import deque

def window_max(values, k):
    # indexes; their values decrease from front to back
    best = deque()
    out = []
    for right, v in enumerate(values):
        while best and values[best[-1]] <= v:
            best.pop()
        best.append(right)
        if best[0] <= right - k:
            best.popleft()
        if right >= k - 1:
            out.append(values[best[0]])
    return out

print(window_max([3, 1, 4, 1, 5, 9, 2, 6], 3))
Predict

The largest value in each window of 3 over 3, 1, 4, 1, 5, 9, 2, 6?

Pick one to see what it prints.
Pick an answer above to see the rest