forked from williamfiset/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SlidingWindowMaximum.java
57 lines (44 loc) · 1.56 KB
/
SlidingWindowMaximum.java
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* This file contain an implementation of the maximum sliding window problem. This code has been
* tested against the judge data on:
*
* <p>https://leetcode.com/problems/sliding-window-maximum/description/
*
* @author William Fiset, [email protected]
*/
package com.williamfiset.algorithms.other;
import java.util.ArrayDeque;
import java.util.Deque;
public class SlidingWindowMaximum {
int[] values;
public int N, lo, hi;
Deque<Integer> deque = new ArrayDeque<>();
public SlidingWindowMaximum(int[] values) {
if (values == null) throw new IllegalArgumentException();
this.values = values;
N = values.length;
}
// Advances the front of the window by one unit
public void advance() {
// Remove all the worse values in the back of the deque
while (!deque.isEmpty() && values[deque.peekLast()] < values[hi])
deque.removeLast(); // Change the '<' sign here ^^^ to '>' for minimum sliding window
// Add the next index to the back of the deque
deque.addLast(hi);
// Increase the window size
hi++;
}
// Retracks the back of the window by one unit
public void shrink() {
// Decrease window size by pushing it forward
lo++;
// Remove elements in the front of the queue whom are no longer
// valid in the reduced window.
while (!deque.isEmpty() && deque.peekFirst() < lo) deque.removeFirst();
}
// Query the current maximum value in the window
public int getMax() {
if (lo >= hi) throw new IllegalStateException("Make sure lo < hi");
return values[deque.peekFirst()];
}
}