1
+ /**
2
+ * This file contain an implementation of the maximum sliding window problem. This code has been
3
+ * tested against the judge data on:
4
+ *
5
+ * <p>https://leetcode.com/problems/sliding-window-maximum/description/
6
+ *
7
+ * @author William Fiset, william.alexandre.fiset@gmail.com
8
+ */
9
+
10
+ import java .util .ArrayDeque ;
11
+ import java .util .Deque ;
12
+
13
+ public class SlidingWindowMaximum {
14
+
15
+ int [] values ;
16
+ public int N , lo , hi ;
17
+
18
+ Deque <Integer > deque = new ArrayDeque <>();
19
+
20
+ public SlidingWindowMaximum (int [] values ) {
21
+ if (values == null ) throw new IllegalArgumentException ();
22
+ this .values = values ;
23
+ N = values .length ;
24
+ }
25
+
26
+ // Advances the front of the window by one unit
27
+ public void advance () {
28
+
29
+ // Remove all the worse values in the back of the deque
30
+ while (!deque .isEmpty () && values [deque .peekLast ()] < values [hi ])
31
+ deque .removeLast (); // Change the '<' sign here ^^^ to '>' for minimum sliding window
32
+
33
+ // Add the next index to the back of the deque
34
+ deque .addLast (hi );
35
+
36
+ // Increase the window size
37
+ hi ++;
38
+ }
39
+
40
+ // Retracks the back of the window by one unit
41
+ public void shrink () {
42
+
43
+ // Decrease window size by pushing it forward
44
+ lo ++;
45
+
46
+ // Remove elements in the front of the queue whom are no longer
47
+ // valid in the reduced window.
48
+ while (!deque .isEmpty () && deque .peekFirst () < lo ) deque .removeFirst ();
49
+ }
50
+
51
+ // Query the current maximum value in the window
52
+ public int getMax () {
53
+ if (lo >= hi ) throw new IllegalStateException ("Make sure lo < hi" );
54
+ return values [deque .peekFirst ()];
55
+ }
56
+ }
0 commit comments