Sliding Window Maximum Monotonic Deque
A monotonic deque keeps window candidates ordered so each index enters and leaves at most once, streaming maxima for sensors and rate windows.
Code
import java.util.ArrayDeque;
import java.util.Deque;
public class SlidingWindowMax {
// 单调(monotonic)递减 deque:队头永远是当前 sliding window 的 maximum
static int[] windowMaxima(int[] values, int k) {
int[] maxima = new int[values.length - k + 1];
Deque<Integer> indices = new ArrayDeque<>();
for (int i = 0; i < values.length; i++) {
// 队尾比当前值小的元素不可能再成为最大值:从尾部弹出
while (!indices.isEmpty() && values[indices.peekLast()] <= values[i]) {
indices.pollLast();
}
indices.offerLast(i);
// 队头已滑出窗口:从头部弹出
if (indices.peekFirst() <= i - k) {
indices.pollFirst();
}
// 窗口填满后输出队头
if (i >= k - 1) {
maxima[i - k + 1] = values[indices.peekFirst()];
}
}
return maxima;
}
public static void main(String[] args) {
int[] readings = {4, 2, 9, 1, 7, 7, 3, 8};
int[] maxima = windowMaxima(readings, 3);
for (int i = 0; i < maxima.length; i++) {
System.out.printf("window %d..%d max = %d%n", i, i + 2, maxima[i]);
}
}
}Why the deque stays monotonic
windowMaxima(values, k) keeps a deque of indices whose values decrease from front to back. Before index i enters, the tail loop while (!indices.isEmpty() && values[indices.peekLast()] <= values[i]) pops every smaller-or-equal candidate — such an element can never be a maximum again while i is in the window. The head then ages out with if (indices.peekFirst() <= i - k), and once i >= k - 1 the head is the current window’s maximum, written straight into maxima[i - k + 1].
The stream of maxima
window 0..2 max = 9
window 1..3 max = 9
window 2..4 max = 9
window 3..5 max = 7
window 4..6 max = 7
window 5..7 max = 8
For readings {4, 2, 9, 1, 7, 7, 3, 8} the value 9 dominates three consecutive windows until it slides out; the tie at 7, 7 survives because the tail loop pops on <=, keeping the later index. Each index enters and leaves the deque at most once, so the whole pass is O(n) — the point of the comment about streaming maxima for sensors and rate windows.
The line that publishes each window
maxima[i - k + 1] = values[indices.peekFirst()];
Reading the answer off the front (never re-scanning the window) is what separates this from the naive O(n·k) approach.
Interactive Tools for This Topic
FAQ
- What does Sliding Window Maximum Monotonic Deque print when run?
- Execute the whole file; each printed line is prefixed with a label like `window`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.