Design a max stack that supports push, pop, top, peekMax and
popMax.
- push(x)
-- Push element x onto stack.
- pop()
-- Remove the element on top of the stack and return it.
- getMax()
-- Retrieve the maximum element in the stack
Example:
MaxStack stack = new MaxStack();
stack.push(5);
stack.push(1);
stack.push(5);
stack.getMax(); -> 5
stack.pop(); -> 1
stack.top(); -> 5
Note:
- -1e7
<= x <= 1e7
- Number
of operations won't exceed 10000.
- The
last four operations won't be called when stack is empty.
Solution:
This problem can be solved with multiple approaches. This
approach makes use of two stacks to get the largest element. we can however
optimize the behavior to use doubly linked list and a treemap.
Comments
Post a Comment