-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path239. Sliding Window Maximum.java
More file actions
35 lines (28 loc) · 1.11 KB
/
239. Sliding Window Maximum.java
File metadata and controls
35 lines (28 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// https://leetcode.com/submissions/detail/829208418/
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int p = 0;
int n = nums.length;
int[] res = new int[n-k+1];
// declaring the dequeue
Deque<Integer> dq = new ArrayDeque<>();
for(int i=0;i<n;i++){
// checking for out of bounadry elements
if(!dq.isEmpty() && dq.peek() == i-k) // for k =3 upto 0 1 2 --> the first subarray
{
dq.poll();
}
//checking if the elements corresponding to the indexes stored are in the decreasing fashion or not
while(!dq.isEmpty() && nums[dq.peekLast()] <= nums[i]){
dq.pollLast();
}
//push in deque is offer
// pushing the current index into the deque
dq.offer(i);
if(i >= k-1){
res[p++] = nums[dq.peek()]; // storing the max value in res array during the starting pnt of each subarray
}
}
return res;
}
}