Data Structures19 sections · 729 units
Open in Course

The Sliding Window Maximum

A classic problem

Given an array numsnums and a window size kk, return an array containing the maximum of each sliding window.

Example: nums=[1,3,1,3,5,3,6,7]nums = [1, 3, -1, -3, 5, 3, 6, 7], k=3k = 3 Windows: [1,3,1],[3,1,3],[1,3,5],[3,5,3],[5,3,6],[3,6,7][1,3,-1], [3,-1,-3], [-1,-3,5], [-3,5,3], [5,3,6], [3,6,7] Maxes: [3,3,5,5,6,7][3, 3, 5, 5, 6, 7] Naive approach: for each window, scan all kk elements to find the max.

Time: O(nk)O(nk). With a monotonic deque, you can do this in O(n)O(n).