Sliding Window Maximum
Problem
A window of size k moves from the left end of the array to the right end, one step at a time. Print the maximum of every window position.
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
A deque of indexes stays sorted by value (largest first). Elements that are older and smaller than a new element are useless, so we drop them. Every index enters and leaves once: O(n) in total.
/*
* Problem : Process an array and a number k.
* Input : n, integers, then k.
* Output : The window maxima.
* Approach: A decreasing 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) {
int[] result = new int[a.length - k + 1];
// Step 1: The deque keeps indexes. Their values are in decreasing order, so the front is the maximum.
java.util.ArrayDeque<Integer> deque = new java.util.ArrayDeque<>();
for (int i = 0; i < a.length; i++) {
// Step 2: Remove the front index when it left the window.
if (!deque.isEmpty() && deque.peekFirst() <= i - k) {
deque.pollFirst();
}
// Step 3: Remove smaller values from the back. They can never be the maximum again.
while (!deque.isEmpty() && a[deque.peekLast()] <= a[i]) {
deque.pollLast();
}
deque.addLast(i);
// Step 4: When the first full window is ready, the front is the maximum.
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 can an older smaller element never be the maximum again?