Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Track the Maximum Element in a Stack.

Objec­tive: In a Stack, keep track of max­i­mum value in it. It might be the top ele­ment in the stack but once it is poped out, the max­i­mum value should be from the rest of the ele­ments in the stack.


  • Cre­ate another another Stack(call it as track) which will keep track of max­i­mum in the given Stack(call it as main).
  • When you insert an ele­ment 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 ele­ment from the track Stack ( say it is ‘a’). Com­pare x and a and which ever is greater, insert it into track Stack.
  • When you pop the ele­ment from the main stack, pop from the track Stack as well
  • So to get to know the max­i­mum ele­ment in the main Stack, peek the ele­ment in the track Stack. . See Exam­ple below.

Thanks Gau­rav Dey for sug­gest­ing this solution.




Com­plete Code:


Max Element is 18
Removing Element 18
Max Element is 14

You may also like...