We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
It seems the editorial solution and several mentioned here are needlessly complex. We do not need to maintain two stacks. Instead, we can use a single stack of integers: For query (1), instead of pushing element X, we simply push max(x, stack.peek()). For query (2), simply pop an element. For query (3), print stack.peek().
In a nutshell, we don't care that X is at the top of the stack if there is an element Y > X further down in the stack, so why not just push Y?
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Maximum Element
You are viewing a single comment's thread. Return to all comments →
[Solution Spoilers]
It seems the editorial solution and several mentioned here are needlessly complex. We do not need to maintain two stacks. Instead, we can use a single stack of integers: For query (1), instead of pushing element X, we simply push max(x, stack.peek()). For query (2), simply pop an element. For query (3), print stack.peek().
In a nutshell, we don't care that X is at the top of the stack if there is an element Y > X further down in the stack, so why not just push Y?