Practice/Snowflake/Leetcode 155. Min Stack
CodingMust
Implement a special stack data structure that supports standard stack operations along with retrieving the maximum element currently in the stack. All operations must execute in O(1) constant time complexity.
Your MaxStack class should support the following methods:
push(x): Add element x to the top of the stackpop(): Remove and return the element at the top of the stacktop(): Return the element at the top of the stack without removing itgetMax(): Return the maximum element currently in the stack without removing itThe key challenge is efficiently tracking which element is the maximum as the stack contents change through push and pop operations.
getMax() should always return the current maximum among all elements in the stackgetMax() should correctly return the new maximum-10^9 <= x <= 10^9 (element values)pop(), top(), and getMax() will only be called when the stack is not emptyExample 1:
` Operations: ["MaxStack", "push", "push", "push", "getMax", "pop", "getMax"] Values: [[], [5], [1], [5], [], [], []] Output: [null, null, null, null, 5, 5, 5]
Explanation: MaxStack maxStack = new MaxStack(); maxStack.push(5); // stack is now [5] maxStack.push(1); // stack is now [5, 1] maxStack.push(5); // stack is now [5, 1, 5] maxStack.getMax(); // returns 5 maxStack.pop(); // returns 5, stack is now [5, 1] maxStack.getMax(); // returns 5 `
Example 2:
` Operations: ["MaxStack", "push", "push", "push", "getMax", "pop", "getMax"] Values: [[], [3], [7], [9], [], [], []] Output: [null, null, null, null, 9, 9, 7]
Explanation: After pushing 3, 7, and 9, the maximum is 9. After popping 9, the new maximum is 7. `