716. Max Stack
Design a max stack that supports the following operations:
push(x): push elementxonto the stack.pop(): remove and return the element on top of the stack.top(): return the element on top of the stack without removing it.peekMax(): return the maximum element in the stack without removing it.popMax(): remove and return the maximum element in the stack. If there is more than one maximum, remove only the one closest to the top.
push, pop, top, and peekMax can be implemented in O(1) time. popMax is allowed to take O(n) time in the straightforward solution: hold the values above the topmost maximum aside, remove it, then restore them.
Examples
Input: [["MaxStack","push","push","push","top","peekMax","popMax","pop","peekMax"],[[],[-11],[-4],[3],[],[],[],[],[]]]
Output: [null,null,null,null,3,3,3,-4,-11]
Input: [["MaxStack","push","push","push","push","top","peekMax","popMax","pop","peekMax"],[[],[0],[7],[-9],[-2],[],[],[],[],[]]]
Output: [null,null,null,null,null,-2,7,7,-2,0]
Hints
Use two stacks: one for regular operations, one to track maximums.
For popMax, you may need to temporarily transfer elements to find the maximum.
Alternatively, use a doubly-linked list with a separate max-tracker structure.
Related Problems
716. Max Stack
Design a max stack that supports the following operations: