What is Sliding Window Maximum
Return the maximum of every contiguous window of length k. A deque of indexes, kept in decreasing order of value, makes each index enter and leave once.
Approach
Visualization & algorithm
The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each index is pushed and popped at most once. |
| Space | O(k) | The deque never holds more than one decreasing run. |
Implementation
from collections import deque
def solve(self, nums, k):
dq, ans = deque(), []
for i, val in enumerate(nums):
if dq and dq[0] <= i-k: dq.popleft()
while dq and nums[dq[-1]] <= val: dq.pop()
dq.append(i)
if i >= k-1: ans.append(nums[dq[0]])
return ans