You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window.
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
Input: nums = [1], k = 1
Output: [1]
Brute force: For each window, scan k elements to find max - O(nk) time.
Optimal: Use a Monotonic Decreasing Deque to track potential maximums:
This is a Sliding Window + Monotonic Deque problem:
deque.front() <= i - knums[i] >= nums[deque.back()]i to backi >= k - 1, add nums[deque.front()] to resultWhy This Works:
1class Solution {
2 public int[] maxSlidingWindow(int[] nums, int k) {
3 int n = nums.length;
4 int[] result = new int[n - k + 1];
5 Deque<Integer> deque = new LinkedList<>(); // Stores indices
6
7 for (int i = 0; i < n; i++) {
8 // Remove indices outside window
9 while (!deque.isEmpty() && deque.peekFirst() <= i - k) {
10 deque.pollFirst();
11 }
12
13 // Maintain decreasing order: remove smaller elements
14 while (!deque.isEmpty() && nums[i] >= nums[deque.peekLast()]) {
15 deque.pollLast();
16 }
17
18 // Add current index
19 deque.offerLast(i);
20
21 // Record maximum for this window
22 if (i >= k - 1) {
23 result[i - k + 1] = nums[deque.peekFirst()];
24 }
25 }
26
27 return result;
28 }
29}
30