Sliding Window Maximum in Java: Explanation & Practice
Find maximum in each sliding window
Problem summary
Given an array and window size k, find the maximum in each window position.
Starter code
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] arr = {1, 3, -1, -3, 5, 3, 6, 7};
int k = 3;
// Find max in each window of size k
// Print maximums space-separated
}
}Expected output and test cases
- Window size 3
3 3 5 5 6 7
- Window size 4
5 5 6 7 7
- Window size 1
1 3 -1 -3 5 3 6 7
Hints
- Use Deque for efficient O(n)
- Store indices, not values
- Remove elements outside window
Related Collections exercises
- Practice Stack Using Queues in Java
- Practice Group Anagrams in Java
- Practice Top K Frequent Elements in Java
Practice all Collections exercises · Run this idea in the Java compiler