Max Stack
Design a max stack that supports push, pop, top, peekMax and popMax.
Example 1:
MaxStack stack = new MaxStack();
stack.push(5);
stack.push(1);
stack.push(5);
stack.top(); -> 5
stack.popMax(); -> 5
stack.top(); -> 1
stack.peekMax(); -> 5
stack.pop(); -> 1
stack.top(); -> 5
Note:
class MaxStack {
Stack<Integer> stack = new Stack<>();
Stack<Integer> maxStack = new Stack<>();;
public void push(int x) {
int max = maxStack.isEmpty() ? x : maxStack.peek();
maxStack.push(max > x ? max : x);
stack.push(x);
}
public int pop() {
maxStack.pop();
return stack.pop();
}
public int top() {
return stack.peek();
}
public int peekMax() {
return maxStack.peek();
}
public int popMax() {
int max = peekMax();
Stack<Integer> buffer = new Stack();
while (top() != max) buffer.push(pop());
pop();
while (!buffer.isEmpty()) push(buffer.pop());
return max;
}
}
push(x)
operation we push the element to both main stack and maxStackpopMax()
, we know what the current maximum is using peekMax()
. We can pop from the main stack until we find that maximum, then push the popped elements back on the main stack.