easy +10 pts

Max Stack Design

Design a stack that supports push, pop, top, and retrieving the maximum element in O(1) time.

Design a `MaxStack` class that behaves like a stack but also allows retrieving the maximum element in constant time. Implement the following methods: - `push(val: int) -> None`: Pushes an integer `val` onto the stack. - `pop() -> int`: Removes and returns the top element of the stack. (Assume the stack is non-empty when called.) - `top() -> int`: Returns the top element without removing it. (Assume the stack is non-empty when called.) - `get_max() -> int`: Returns the maximum element currently in the stack without removing it. (Assume the stack is non-empty when called.) All operations must run in O(1) time. You may use extra space as needed. Additionally, implement a runner function `MaxStack_run(ops: list, values: list) -> list` that executes a sequence of operations on a fresh `MaxStack` instance and returns a list of results. The `ops` list contains method names as strings; `values` list contains corresponding integer arguments for `push` or `None` for other operations. For each operation, append the return value (or `None` for void methods) to the result list.

Constraints

0 <= val <= 10^9 (for push) Total number of method calls will not exceed 10^5. pop(), top(), get_max() will only be called on non-empty stack.

Example

>>> s = MaxStack()
>>> s.push(5)
>>> s.push(1)
>>> s.push(5)
>>> s.get_max()
5
>>> s.pop()
5
>>> s.get_max()
5
>>> s.top()
1
>>> s.pop()
1
>>> s.get_max()
5
>>> s.pop()
5
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Maintain a second stack that stores the maximum value seen so far.
When pushing, compare the new value to the current maximum and push the larger onto the max stack.
When popping, pop from both the main stack and the max stack.
get_max simply returns the top of the max stack.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.