File tree 1 file changed +35
-0
lines changed
1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments