EPI Solution:
https://github.com/epibook/epibook.github.io/blob/master/solutions/java/src/main/java/com/epi/QueueWithMaxUsingDeque.java
public static class Queue<T extends Comparable<T>> {
private LinkedList<T> q = new LinkedList<>();
private LinkedList<T> d = new LinkedList<>();
public void enqueue(T x) {
q.addFirst(x);
while (!d.isEmpty() && d.getLast().compareTo(x) < 0) {
d.removeLast();
}
d.addLast(x);
}
public T dequeue() {
if (!q.isEmpty()) {
T ret = q.removeLast();
if (ret.equals(d.getFirst())) {
d.removeFirst();
}
return ret;
}
throw new RuntimeException("empty queue");
}
public T max() {
if (!d.isEmpty()) {
return d.getFirst();
}
throw new RuntimeException("empty queue");
}
public T head() {
return q.getLast();
}
}
https://github.com/epibook/epibook.github.io/blob/master/solutions/java/src/main/java/com/epi/QueueWithMaxUsingDeque.java
public static class Queue<T extends Comparable<T>> {
private LinkedList<T> q = new LinkedList<>();
private LinkedList<T> d = new LinkedList<>();
public void enqueue(T x) {
q.addFirst(x);
while (!d.isEmpty() && d.getLast().compareTo(x) < 0) {
d.removeLast();
}
d.addLast(x);
}
public T dequeue() {
if (!q.isEmpty()) {
T ret = q.removeLast();
if (ret.equals(d.getFirst())) {
d.removeFirst();
}
return ret;
}
throw new RuntimeException("empty queue");
}
public T max() {
if (!d.isEmpty()) {
return d.getFirst();
}
throw new RuntimeException("empty queue");
}
public T head() {
return q.getLast();
}
}
Compute the maximum of a sliding window SlidingWindow.java
public static class TrafficElement implements Comparable<TrafficElement> {
private final int time, volume;
public TrafficElement(int time, int volume) {
this.time = time;
this.volume = volume;
}
public int getTime() {
return time;
}
public int getVolume() {
return volume;
}
@Override
public int compareTo(TrafficElement o) {
int result = volume - o.getVolume();
return result != 0 ? result : time - o.getTime();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
return compareTo((TrafficElement) o) == 0;
}
}
public static void trafficVolumes(List<TrafficElement> A, int w) {
Queue<TrafficElement> Q = new Queue<>();
for (int i = 0; i < A.size(); i++) {
Q.enqueue(A.get(i));
while (A.get(i).getTime() - Q.head().getTime() > w) {
Q.dequeue();
}
System.out.println("Max after inserting " + i + " is "
+ Q.max().getVolume());
}
}