Sliding Window Maximum

HardAcc. 62.4%
+60 XP 30

Monotonic Dominance

To find the max in O(n), use a Deque to store indices. Maintain the deque so that the elements are in descending order.

The Assignment

Your function receives nums and k.

  1. Iterate through nums.
  2. Remove indices from the front that are out of the window (< i - k + 1).
  3. Remove indices from the back whose values are smaller than the current value (nums[i]).
  4. Add current index to back.
  5. If window is full, print nums[deque[0]].

01EXAMPLE 1

Inputnums=[1,3,-1,-3,5,3,6,7], k=3
Output3 3 5 5 6 7

Explanation: Current peaks for each window.

Constraints

  • Must solve in O(n) time.
Data StructuresQueueSliding Window
JavaScript
Loading...
1 Hidden

Input Arguments

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

Expected Output

3
3
5
5
6
7

Click RUN to test your solution