Track the Maximum Element in a Stack.
Objective: In a Stack, keep track of maximum value in it. It might be the top element in the stack but once it is poped out, the maximum value should be from the rest of the elements in the stack.
- Create another another Stack(call it as track) which will keep track of maximum in the given Stack(call it as main).
- When you insert an element in the main stack for the first time ( means it is empty), insert it in the track Stack as well.
- Now onwards when you insert a new element(say it is x) in the main Stack, peek() the element from the track Stack ( say it is ‘a‘). Compare x and a and which ever is greater, insert it into track Stack.
- When you pop the element from the main stack, pop from the track Stack as well
- So to get to know the maximum element in the main Stack, peek the element in the track Stack. . See Example below.
Thanks Gaurav Dey for suggesting this solution.
Max Element is 18 Removing Element 18 Max Element is 14
Top Companies Interview Questions..-
If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.