Created
July 28, 2016 18:55
-
-
Save crearo/f285f8385a2f1fe23717520f1a1c93bf to your computer and use it in GitHub Desktop.
A data structure with getMax(), getMin() in O(1) time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was not written by me, but I really like the implementation. It is taken from this answer on SO.