Problem 577
Sliding Window Median
Hard · 30 pts · Array, Sliding Window, Binary Search, Sorting
Problem
For every window of K consecutive elements, from the window starting at index 0 to the one ending at the last index, find the median of the window. K is always odd, so the median is the middle value of the window when it is sorted, and it is always an integer. Keep the current window in a sorted list: when the window slides, remove the element that leaves and insert the one that enters, each found by binary search.
Input
The first line contains N and K. The second line contains N integers.
Output
Print the N - K + 1 medians separated by spaces.
Constraints
1 <= K <= N <= 20000; K is odd; -10^9 <= A[i] <= 10^9
Example input
8 3 1 3 -1 -3 5 3 6 7
Example output
1 -1 -1 3 5 6
Explanation
With 1 3 -1 -3 5 3 6 7 and K = 3, the windows are [1 3 -1], [3 -1 -3], [-1 -3 5], [-3 5 3], [5 3 6] and [3 6 7]. Their middle values are 1 -1 -1 3 5 6.