Skills101
← All coding problems

Sliding Window Maximum

hardSliding Window+40 XPTime limit 2s

A window of size k slides over the array from left to right, one position at a time. Print the maximum inside the window at every position.

Input:

  • line 1: n k
  • line 2: n integers

Output: n − k + 1 numbers on one line — the maximum of each window.

Constraints: 1 ≤ k ≤ n ≤ 10⁵, −10⁴ ≤ a[i] ≤ 10⁴.

Think about it: recomputing each window is O(n·k) — too slow when k is large. Keep a deque of indices whose values are decreasing; the front is always the current maximum. Every index enters and leaves once: O(n).

Sample input 1

8 3
1 3 -1 -3 5 3 6 7

Sample output 1

3 3 5 5 6 7

Sample input 2

1 1
1

Sample output 2

1

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.