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 positionMax
----------------------
[1 3 -1] -3 5 3 6 73
1 [3 -1 -3] 5 3 6 73
1 3 [-1 -3 5] 3 6 75
1 3 -1 [-3 5 3] 6 75
1 3 -1 -3 [5 3 6] 76
1 3 -1 -3 5 [3 6 7]7
Input: nums = [1], k = 1
Output: [1]
Constraints:

Contents

In this approach, we will use a Deque data structure (double ended queue) to store elements such a way that, it contains elements in decreasing order. So, whenever we reach a sliding window of length k, we can simply poll the head element and add that result.

So, how do we achieve this ?

We will start iterating through the input array nums, and store the element at head position in the Deque.

By doing so, we are keeping lergest element at the head. When we reach a sliding window of length k, take the element at head position from Deque and add it to the result, also move sliding window to next position, when we move left position of sliding window, check if the head position is that left pointer element, if it is, then remove it from the Deque.

Let's understand this with an example, nums = [1,3,-1,-3,5,3,6,7] and

import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; public class SlidingWindowMaximum { static int[] maxSlidingWindow(int[] nums, int k) { Deque<Integer> q = new ArrayDeque<>(nums.length); int left =0; int right =0; int[] ans = new int[nums.length - k+1]; int ai =0; while (right <nums.length) { while(!q.isEmpty() && q.peekLast() < nums[right]){ q.pollLast(); } q.offerLast(nums[right]); if(k<=right-left+1) { ans[ai++] = q.peekFirst(); if(q.peekFirst() == nums[left++]) { q.pollFirst(); } } right++; } return ans; } public static void main(String[] args) { System.out.println(Arrays.toString(maxSlidingWindow(new int[]{1,3,-1,-3,5,3,6,7},3))); } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time, where n is the length of input array nums.
Space complexity: O(n), since we are storing input array elements into a Deque.

Above implementations source code can be found at GitHub link for Java code