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

  1. Use Deque for efficient O(n)
  2. Store indices, not values
  3. Remove elements outside window

Related Collections exercises

Practice all Collections exercises · Run this idea in the Java compiler