All problems

Problem 134

Sliding Window Maximum

Hard · 30 pts · Array, Queue, Sliding Window, Monotonic Queue

Problem

You are given an array of N integers and a window size K. A window covering K consecutive elements slides from the left end of the array to the right end, one position at a time. Print the maximum of every window, which gives N - K + 1 values. Recomputing each maximum takes O(N × K). Instead, keep a deque of indices whose values are in decreasing order: drop indices from the front once they leave the window, and drop smaller values from the back before adding a new element. The front of the deque is always the window maximum, giving O(N) overall.

Input

First line: integers N and K. Second line: N space-separated integers.

Output

Print N - K + 1 values, space-separated.

Constraints

1 <= K <= N <= 100000; -10000 <= A[i] <= 10000

Example input

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

Example output

3 3 5 5 6 7

Explanation

The windows of size 3 over 1 3 -1 -3 5 3 6 7 are [1 3 -1], [3 -1 -3], [-1 -3 5], [-3 5 3], [5 3 6] and [3 6 7]. Their maxima are 3 3 5 5 6 7.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Simplify Path Next: Last Stone Weight