Loading problem...
Design and implement a specialized stack data structure that not only supports standard stack operations but also provides efficient access to and removal of the maximum element within the stack at any given time.
Your task is to create the MaximumTrackingStack class with the following methods:
x onto the top of the stack.Your implementation must achieve O(1) time complexity for the top operation and O(log n) time complexity for all other operations, where n is the number of elements in the stack.
This problem challenges you to combine multiple data structures to achieve efficient maximum tracking while maintaining the fundamental LIFO (Last-In-First-Out) behavior of a stack.
["MaximumTrackingStack", "push", "push", "push", "top", "popMaximum", "top", "peekMaximum", "pop", "top"]
[[], [5], [1], [5], [], [], [], [], [], []][null, null, null, null, 5, 5, 1, 5, 1, 5]MaximumTrackingStack stk = new MaximumTrackingStack(); stk.push(5); // Stack: [5] - Top element is 5, maximum is 5 stk.push(1); // Stack: [5, 1] - Top is 1, but maximum is still 5 stk.push(5); // Stack: [5, 1, 5] - Top is 5, maximum is 5 (topmost occurrence) stk.top(); // Returns 5 - Stack unchanged: [5, 1, 5] stk.popMaximum(); // Returns 5 - Removes topmost max, Stack: [5, 1] stk.top(); // Returns 1 - Stack unchanged: [5, 1] stk.peekMaximum(); // Returns 5 - Maximum is 5, Stack unchanged: [5, 1] stk.pop(); // Returns 1 - Stack: [5] stk.top(); // Returns 5 - Stack unchanged: [5]
["MaximumTrackingStack", "push", "push", "push", "pop", "pop", "pop"]
[[], [1], [2], [3], [], [], []][null, null, null, null, 3, 2, 1]This demonstrates basic LIFO behavior. Elements 1, 2, 3 are pushed, then popped in reverse order: 3, 2, 1.
["MaximumTrackingStack", "push", "push", "push", "peekMaximum", "popMaximum", "peekMaximum"]
[[], [3], [7], [2], [], [], []][null, null, null, null, 7, 7, 3]After pushing 3, 7, 2: the stack is [3, 7, 2]. The maximum is 7. After popMaximum() removes 7, the stack becomes [3, 2] and the new maximum is 3.
Constraints