Track the Maximum Element in a Stack.

Objective: In a Stack, keep track of the maximum value in it. It might be the top element in the stack but once it is popped out, the maximum value should be from the rest of the elements in the stack.

Approach:

  • Create another Stack(call it track) which will keep track of the maximum in the given Stack(call it main).
  • When you insert an element in the main stack for the first time (which 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 whichever 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 at the element in the track Stack. . See the Example below.

Thanks, Gaurav Dey for suggesting this solution.

Track-the-Maximum-Element-in-a-Stack

Code:

Output:

Max Element is 18
Removing Element 18
Max Element is 14