import java.util.*; class MethodsToSolution { Deque<Integer> windowQueue = new ArrayDeque<>(); int[] nums; public void updatedWindowQueue(int index, int k) { if (!windowQueue.isEmpty() && windowQueue.peekFirst() == index - k) { windowQueue.pollFirst(); } while (!windowQueue.isEmpty() && nums[index] > nums[windowQueue.peekLast()]) { windowQueue.pollLast(); } } public int[] maxSlidingWindow(int[] nums, int k) { if (nums.length * k == 0) { return new int[0]; } if (k == 1) { return nums; } this.nums = nums; int maximumIndex = 0; for (int i = 0; i < k; i++) { updatedWindowQueue(i, k); windowQueue.offerLast(i); if (nums[i] > nums[maximumIndex]) { maximumIndex = i; } } int[] result = new int[nums.length - k + 1]; result[0] = nums[maximumIndex]; for (int i = k; i < nums.length; i++) { updatedWindowQueue(i, k); windowQueue.offerLast(i); result[i - k + 1] = nums[windowQueue.peekFirst()]; } return result; }}class Solution { public static void main(String[] args) { MethodsToSolution methodsToSolution = new MethodsToSolution(); int[] nums1 = {1,3,-1,-3,5,3,6,7}; int k1 = 3; int[] nums2 = {1}; int k2 = 1; System.out.println(Arrays.toString( methodsToSolution.maxSlidingWindow(nums1, k1))); System.out.println(Arrays.toString( methodsToSolution.maxSlidingWindow(nums2, k2))); }}