This is not all that difficult if you think about it. Regular stacks support push() and pop() functions. We need to add a new read-only property, maximum. You can’t just add a new variable to track the maximum because when the stack is popped you wouldn’t be know how to update the maximum variable without scanning through all items in the stack which would require you to pop and re-push each item, which is downright ugly. So we need to keep some auxiliary list of the stack items so we can update the maximum variable after we pop items.
A clever way to do that is to use another stack that stores the maximum of all items in the stack. The maximum value is calculated when items are pushed to the stack and when items are popped from the stack we also pop from the maxStack to reveal the new maximum value.
Let’s call this stack max_stack. This stack will always have the maximum value at the top.
Modify ‘push’ and ‘pop’ operations as follows:
push:
If the element being pushed is less than the top element of max_stack then push it on ‘max_stack’ as well.
Else, push the top element of ‘max_stack’ again on max_stack.
pop:
Every time you pop an element from the original stack, pop from max_stack as well.