AceYourInterviews
Checking sign-in…

27. Sliding Window Maximum

AdvancedMonotonic deque of undominated indices

Slide a window of exactly k positions from the beginning of the array to the end. For each possible placement, report the largest value currently inside that window.

Produce one result for each complete window, in left-to-right order. Duplicate maximum values and values leaving the window must be handled correctly.

Example 1

Input

nums=[1,3,-1,-3,5,3,6,7], k=3

Output

[3,3,5,5,6,7]

Explanation: Each output belongs to the next complete length-three interval.

Example 2

Input

nums=[-4,-2,-5], k=2

Output

[-2,-2]

Explanation: All-negative windows still have negative maxima.

Constraints

  • 0 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
  • 1 <= k <= nums.length
  • An empty array has no valid window width.
Hints
Hint 1

Can an older smaller value ever beat a newer larger value before the newer one expires?

Hint 2

Keep undominated indices in decreasing value order.

Hint 3

Expire from the front, prune from the back, append right, then read the front.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Expiration and dominated-candidate removal

[1,3,-1,-3,5,3,6,7]
3
[3,3,5,5,6,7]