Skip to content

Commit 127004c

Browse files
committed
using deque to maintain maximum elements of a window
1 parent b0983a1 commit 127004c

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Deque/maxSlidingWindow.java

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
public int[] maxSlidingWindow(int[] nums, int k) {
3+
/*
4+
We use Double ended queue to maintain the greatest element at the front
5+
of the queue. And smaller elements behind it.
6+
If the element is not in the sliding window, we remove it from the queue.
7+
1. We check if the element at the front of deque is in the window or not.
8+
2. We check if the element at the end of deque is less than current element.
9+
3. we add the current element to the end of the deque to maintain the order.
10+
*/
11+
12+
if (nums == null || nums.length == 0 ||nums.length < k) return new int[0];
13+
14+
Deque<Integer> dq = new ArrayDeque<>();
15+
int[] res = new int[nums.length - k + 1];
16+
int i = 0;
17+
while(i < nums.length) {
18+
// from the front of deque
19+
if (!dq.isEmpty() && dq.peekFirst() == i - k) { // storing indexes
20+
dq.pollFirst();
21+
}
22+
// from the end of deque, keep removing till element is smaller than current element
23+
while(!dq.isEmpty() && nums[dq.peekLast()] < nums[i]) {
24+
dq.pollLast();
25+
}
26+
dq.offerLast(i);
27+
28+
if (i >= k-1) {
29+
res[i-k+1] = nums[dq.peekFirst()]; // max element will be at top
30+
}
31+
i++;
32+
}
33+
return res;
34+
}
35+
}

0 commit comments

Comments
 (0)