Untitled
public class SlidingWindowMaximum { public int[] maxSlidingWindow(int[] nums, int k) { int n = nums.length; int[] result = new int[n - k + 1]; Deque<Integer> deque = new LinkedList<>(); int i = 0, j = 0,idx=0; // Process the first k elements while (j < k) { // Remove smaller elements as they are not useful while (!deque.isEmpty() && nums[deque.peekLast()] <= nums[j]) { deque.pollLast(); } deque.addLast(j); j++; } // Store the maximum for the first window result[idx++] = nums[deque.peekFirst()]; // Process the rest of the elements while (j < n) { // Remove smaller elements as they are not useful while (!deque.isEmpty() && nums[deque.peekLast()] <= nums[j]) { deque.pollLast(); } deque.addLast(j); i++; // Remove elements not in the current window if (!deque.isEmpty() && deque.peekFirst() < i) { deque.pollFirst(); } // Store the maximum for the current window result[idx++] = nums[deque.peekFirst()]; j++; } return result; } }
Leave a Comment