What is Max in Window
Return the maximum of every contiguous block of length k, from left to right. A deque stores indices in decreasing order of value. The front index is the max of the current window.
1 3 -1 -3 5 3 6 7 k = 3 3 3 5 5 6 7
Approach
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step. L and R mark the window.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each index is pushed once and popped once. |
| Memory | O(k) | The deque holds at most one index per window slot. |
Implementation
def max_window(a, k):
from collections import deque
dq, ans = deque(), []
for i, v in enumerate(a):
while dq and dq[0] <= i - k:
dq.popleft()
while dq and a[dq[-1]] <= v:
dq.pop()
dq.append(i)
if i >= k - 1:
ans.append(a[dq[0]])
return ans