given an array and a number k find the max elements of each of its subarrays of length k keep indexes of good candidates in deque d the indexes in d are from the current window they re increasing and their corresponding nums are decreasing then the first deque element is the index of the largest window value for each index i 1 pop from the end indexes of smaller elements they ll be useless 2 append the current index 3 pop from the front the index i k if it s still in the deque it falls out of the window 4 if our window has reached size k append the current window maximum to the output queue storing indexes of elements
import collections


def max_sliding_window(arr, k):
    qi = collections.deque()  
    result = []
    for i, n in enumerate(arr):
        while qi and arr[qi[-1]] < n:
            qi.pop()
        qi.append(i)
        if qi[0] == i - k:
            qi.popleft()
        if i >= k - 1:
            result.append(arr[qi[0]])
    return result