Max Stack
Design a stack supporting push, pop (remove/return the top), top (peek the top), peekMax (return the maximum element), and popMax (remove and return the maximum element). When several elements share the maximum value, popMax must remove the one closest to the top.
Open official problem prompt ↗Serve two orderings of the same elements at once: last-in-first-out for top/pop and largest-first (most recent on ties) for peekMax/popMax.
Two librarians share one collection: one shelves books by arrival time, the other by height. When either lends a book out, they leave a sticky note (the removed set) so the other librarian knows to skip that copy when they next reach for it.
- Input
- MaxStack(); push(5); push(1); push(5); top(); popMax(); top(); peekMax(); pop(); top()
- Output
- [null, null, null, null, 5, 5, 1, 5, 1, 5]
- Why
- Stack is [5,1,5]; top is 5; popMax removes the topmost 5 leaving [5,1]; top is 1; peekMax is 5; pop removes 1 leaving [5]; top is 5.
-10^7 <= x <= 10^7At most 10^5 calls to push, pop, top, peekMax, and popMaxpop, top, peekMax, popMax are only called on a non-empty stack