Practice/LinkedIn/Leetcode 716. Max Stack
CodingMust
Design a specialized stack data structure that supports standard stack operations plus the ability to efficiently retrieve and remove the maximum element. Your implementation must provide the following operations:
The key challenge is handling popMax() efficiently when the maximum element is not at the top of the stack. After removing the maximum, the relative order of remaining elements must be preserved.
Example 1:
` Operations: push(5), push(1), push(5) Stack state: [5, 1, 5] (bottom to top)
top() → 5 (most recent element) popMax() → 5 (removes top 5, most recent max) top() → 1 (now top element) peekMax() → 5 (first 5 is still max) pop() → 1 (removes current top) top() → 5 (only element remaining) `
Example 2:
` Operations: push(3), push(7), push(2), push(7) Stack state: [3, 7, 2, 7] (bottom to top)
peekMax() → 7 (maximum value) popMax() → 7 (removes most recent 7) Stack state: [3, 7, 2] top() → 2 (top unchanged) popMax() → 7 (removes remaining 7) Stack state: [3, 2] `
Example 3:
` Operations: push(1), push(2), push(3), push(4) Stack state: [1, 2, 3, 4] (ascending order)
popMax() → 4 popMax() → 3 popMax() → 2 top() → 1 (only element left) `