716. Max Stack

Design a max stack that supports the following operations:

  • push(x): push element x onto 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]
Hints
Related Problems

716. Max Stack

Design a max stack that supports the following operations: