Sliding Window Maximum (Deque)
Problem
Given an array a and a window size k, print the maximum of every window of k neighbouring numbers, from left to right, separated by spaces. Do it in O(n) with a deque that keeps indexes of useful candidates.
Constraints
- 1 <= k <= n <= 10^5
Examples
Input
8 1 3 -1 -3 5 3 6 7 3
Output
3 3 5 5 6 7
Solutions
Each index enters and leaves the deque once, so the total work is O(n), better than the O(n*k) brute force. The JavaScript version uses an array with a head pointer because shift() is slow.
/*
* Problem : Window maxima.
* Input : n, array, k.
* Output : Maxima.
* Approach: Deque.
* Time : O(n)
* Space : O(k)
* Java : 8 or newer.
*/
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int[] solve(int[] a, int k) {
// Step 1: The deque holds indexes. Their values go down from front to back, so the front is the maximum.
java.util.ArrayDeque<Integer> deque = new java.util.ArrayDeque<>();
int[] result = new int[a.length - k + 1];
for (int i = 0; i < a.length; i++) {
// Step 2: Remove the front index when it has left the window.
if (!deque.isEmpty() && deque.peekFirst() <= i - k) {
deque.pollFirst();
}
// Step 3: Remove smaller values from the back. They can never be a maximum again.
while (!deque.isEmpty() && a[deque.peekLast()] <= a[i]) {
deque.pollLast();
}
deque.addLast(i);
// Step 4: When the first window is full, the front is the answer for this window.
if (i >= k - 1) {
result[i - k + 1] = a[deque.peekFirst()];
}
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
int k = scanner.nextInt();
System.out.println(Arrays.stream(solve(a, k)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
}
}
Hints (1)
- Why do we keep indexes and not values?