VOOZH about

URL: https://www.geeksforgeeks.org/dsa/tracking-current-maximum-element-in-a-stack/

⇱ Tracking current Maximum Element in a Stack - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Tracking current Maximum Element in a Stack

Last Updated : 16 Feb, 2023

Given a Stack, keep track of the maximum value in it. The maximum value may be the top element of the stack, but once a new element is pushed or an element is popped from the stack, the maximum element will be now from the rest of the elements.

Examples: 

Input : 4 19 7 14 20
Output : Max Values in stack are 

         4 19 19 19 20

Input : 40 19 7 14 20 5
Output :  Max Values in stack are 

         40 40 40 40 40 40


Method 1 (Brute-force)

We keep pushing the elements in the main stack and whenever we are asked to return the maximum element, we traverse the stack and print the max element.

Time Complexity : O(n) 
Auxiliary Space : O(1)

Method 2 (Efficient): An efficient approach would be to maintain an auxiliary stack while pushing element in the main stack. This auxiliary stack will keep track of the maximum element. 

Below is the step by step algorithm to do this

  1. Create an auxiliary stack, say 'trackStack' to keep the track of maximum element
  2. Push the first element to both mainStack and the trackStack. 
  3. Now from the second element, push the element to the main stack. Compare the element with the top element of the track stack, if the current element is greater than the top of trackStack then push the current element to trackStack otherwise push the top element of trackStack again into it. 
  4. If we pop an element from the main stack, then pop an element from the trackStack as well. 
  5. Now to compute the maximum of the main stack at any point, we can simply print the top element of Track stack. 


Step by step explanation : 

Suppose the elements are pushed on to the stack in the order {4, 2, 14, 1, 18} 

  • Step 1 : Push 4, Current max : 4 
  • Step 2 : Push 2, Current max : 4 
  • Step 3 : Push 14, Current max : 14 
  • Step 4 : Push 1, Current max : 14 
  • Step 5 : Push 18, Current max : 18 
  • Step 6 : Pop 18, Current max : 14

👁 Image

Below is the implementation of the above approach: 


Output
20
20
50

Time Complexity : O(1) 
Auxiliary Complexity : O(n)

Comment
Article Tags:
Article Tags: