Skip to content

Instantly share code, notes, and snippets.

@crearo
Created July 28, 2016 18:55
Show Gist options
  • Save crearo/f285f8385a2f1fe23717520f1a1c93bf to your computer and use it in GitHub Desktop.
Save crearo/f285f8385a2f1fe23717520f1a1c93bf to your computer and use it in GitHub Desktop.
A data structure with getMax(), getMin() in O(1) time
public class StackWithMinMax extends Stack<Integer> {
private Stack<Integer> minStack;
private Stack<Integer> maxStack;
public StackWithMinMax () {
minStack = new Stack<Integer>();
maxStack = new Stack<Integer>();
}
public void push(int value){
if (value <= min()) { // Note the '=' sign here
minStack.push(value);
}
if (value >= max()) {
maxStack.push(value);
}
super.push(value);
}
public Integer pop() {
int value = super.pop();
if (value == min()) {
minStack.pop();
}
if (value == max()) {
maxStack.pop();
}
return value;
}
public int min() {
if (minStack.isEmpty()) {
return Integer.MAX_VALUE;
} else {
return minStack.peek();
}
}
public int max() {
if (maxStack.isEmpty()) {
return Integer.MIN_VALUE;
} else {
return maxStack.peek();
}
}
}
@crearo
Copy link
Author

crearo commented Jul 28, 2016

This was not written by me, but I really like the implementation. It is taken from this answer on SO.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment