69. Sliding Window Maximum
Topic :
Difficulty :
hard
Problem Link :
problem statement
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.
Example 1:
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
Example 2:
Input: nums = [1], k = 1
Output: [1]
Constraints:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
1 <= k <= nums.length
solution
import java.io.*;
import java.util.*;
class SlidingWindowMaximum
{
public static void main(String args[]){
int nums[]={1,3,-1,-3,5,3,6,7};
int k=3;
System.out.println(Arrays.toString(maxSlidingWindow(nums,k)));
}
static int[] maxSlidingWindow(int[] nums, int k) {
int n=nums.length;
int []ans=new int[n-k+1];// no of possible subarrays of size k
int x=0;
ArrayDeque<Integer> deque=new ArrayDeque<>();
int i=0;
//for first k elements
for(;i<k;i++){
//add indexes to the deque
//maintain the deque in a decreasing fashion
// the front element will always be the max of the curr window
// add elements at the last
// while adding if the ele to be added is greater than the last element of the deque
// remove the elemnts to maintain the decreasing fashion
while(!deque.isEmpty() && nums[i]>=nums[deque.peekLast()])
deque.removeLast();
deque.addLast(i);
}
//for the remaining elements
for(;i<nums.length;i++)
{
// add the max element for the curr subarray of size k
ans[x++]=nums[deque.peek()];
//remove elements that are not in the curr window
// the window range should be i-k+1 to i
while(!deque.isEmpty() && deque.peek()<=i-k)
deque.removeFirst();
//add indexes to the deque
//maintain the deque in a decreasing fashion
// the front element will always be the max of the curr window
// add elements at the last
// while adding if the ele to be added is greater than the last element of the deque
// remove the elemnts to maintain the decreasing fashion
while(!deque.isEmpty() && nums[i]>=nums[deque.peekLast()])
deque.removeLast();
deque.addLast(i);
}
ans[x++]=nums[deque.peek()]; // add the max element for the last window
return ans;
}
}