Complete the code to initialize the deque for sliding window maximum.
Deque<Integer> deque = new [1]<>();We use LinkedList to create a deque in Java because it implements the Deque interface.
Complete the code to remove indices from the deque that are out of the current window.
if (!deque.isEmpty() && deque.peekFirst() [1] i - k + 1) { deque.pollFirst(); }
We remove indices from the front of the deque if they are less than the start index of the current window (i - k + 1).
Fix the error in the code that removes smaller elements from the deque's end.
while (!deque.isEmpty() && nums[deque.peekLast()] [1] nums[i]) { deque.pollLast(); }
We remove elements from the deque's end while they are smaller than the current element to maintain decreasing order.
Fill both blanks to correctly add the current index and record the max for the window.
deque.offerLast([1]); if (i >= k - 1) result[i - k + 1] = nums[[2]];
We add the current index i to the deque and record the max element at the front of the deque for the current window.
Fill all three blanks to complete the sliding window maximum function.
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null || nums.length == 0) return new int[0];
int n = nums.length;
int[] result = new int[n - k + 1];
Deque<Integer> deque = new [1]<>();
for (int i = 0; i < n; i++) {
if (!deque.isEmpty() && deque.peekFirst() [2] i - k + 1) {
deque.pollFirst();
}
while (!deque.isEmpty() && nums[deque.peekLast()] [3] nums[i]) {
deque.pollLast();
}
deque.offerLast(i);
if (i >= k - 1) result[i - k + 1] = nums[deque.peekFirst()];
}
return result;
}The function uses a LinkedList as a deque. It removes indices out of the window with < and removes smaller elements with < to maintain the max at the front.
