Tracking current Maximum Element in a Stack

19 Jan, 2022
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:  
Create an auxiliary stack, say ‘trackStack’ to keep the track of maximum elementPush the first element to both mainStack and the trackStack.  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.  If we pop an element from the main stack, then pop an element from the trackStack as well.  Now to compute the maximum of the main stack at any point, we can simply print the top element of Track stack.  
Create an auxiliary stack, say ‘trackStack’ to keep the track of maximum element
Push the first element to both mainStack and the trackStack.  
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.  
If we pop an element from the main stack, then pop an element from the trackStack as well.  
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 
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ program to keep track of maximum// element in a stack#include <bits/stdc++.h>using namespace std; class StackWithMax{    // main stack    stack<int> mainStack;     // stack to keep track of max element    stack<int> trackStack; public:    void push(int x)    {        mainStack.push(x);        if (mainStack.size() == 1)        {            trackStack.push(x);            return;        }         // If current element is greater than        // the top element of track stack, push        // the current element to track stack        // otherwise push the element at top of        // track stack again into it.        if (x > trackStack.top())            trackStack.push(x);        else            trackStack.push(trackStack.top());    }     int getMax()    {        return trackStack.top();    }     int pop()    {        mainStack.pop();        trackStack.pop();    }}; // Driver program to test above functionsint main(){    StackWithMax s;    s.push(20);    cout << s.getMax() << endl;    s.push(10);    cout << s.getMax() << endl;    s.push(50);    cout << s.getMax() << endl;    return 0;}
// Java program to keep track of maximum// element in a stackimport java.util.*;class GfG { static class StackWithMax{    // main stack    static Stack<Integer> mainStack = new Stack<Integer> ();     // Stack to keep track of max element    static Stack<Integer> trackStack = new Stack<Integer> (); static void push(int x)    {        mainStack.push(x);        if (mainStack.size() == 1)        {            trackStack.push(x);            return;        }         // If current element is greater than        // the top element of track stack, push        // the current element to track stack        // otherwise push the element at top of        // track stack again into it.        if (x > trackStack.peek())            trackStack.push(x);        else            trackStack.push(trackStack.peek());    }     static int getMax()    {        return trackStack.peek();    }     static void pop()    {        mainStack.pop();        trackStack.pop();    }}; // Driver program to test above functionspublic static void main(String[] args){    StackWithMax s = new StackWithMax();    s.push(20);    System.out.println(s.getMax());    s.push(10);    System.out.println(s.getMax());    s.push(50);    System.out.println(s.getMax());}}
# Python3 program to keep track of# maximum element in a stack class StackWithMax:    def __init__(self):                 # main stack        self.mainStack = []             # stack to keep track of        # max element        self.trackStack = []     def push(self, x):        self.mainStack.append(x)        if (len(self.mainStack) == 1):            self.trackStack.append(x)            return         # If current element is greater than        # the top element of track stack,        # append the current element to track        # stack otherwise append the element        # at top of track stack again into it.        if (x > self.trackStack[-1]):            self.trackStack.append(x)        else:            self.trackStack.append(self.trackStack[-1])     def getMax(self):        return self.trackStack[-1]     def pop(self):        self.mainStack.pop()        self.trackStack.pop() # Driver Codeif __name__ == '__main__':     s = StackWithMax()    s.push(20)    print(s.getMax())    s.push(10)    print(s.getMax())    s.push(50)    print(s.getMax()) # This code is contributed by PranchalK
// C# program to keep track of maximum// element in a stackusing System;using System.Collections.Generic; class GfG{ public class StackWithMax{    // main stack    static Stack<int> mainStack = new Stack<int> ();     // stack to keep track of max element    static Stack<int> trackStack = new Stack<int> ();     public void push(int x)    {        mainStack.Push(x);        if (mainStack.Count == 1)        {            trackStack.Push(x);            return;        }         // If current element is greater than        // the top element of track stack, push        // the current element to track stack        // otherwise push the element at top of        // track stack again into it.        if (x > trackStack.Peek())            trackStack.Push(x);        else            trackStack.Push(trackStack.Peek());    }     public int getMax()    {        return trackStack.Peek();    }     public void pop()    {        mainStack.Pop();        trackStack.Pop();    }}; // Driver codepublic static void Main(){    StackWithMax s = new StackWithMax();    s.push(20);    Console.WriteLine(s.getMax());    s.push(10);    Console.WriteLine(s.getMax());    s.push(50);    Console.WriteLine(s.getMax());}} /* This code contributed by PrinciRaj1992 */
<script>    // Javascript program to keep track of maximum    // element in a stack         // main stack    let mainStack = [];       // stack to keep track of max element    let trackStack = [];       function push(x)    {        mainStack.push(x);        if (mainStack.length == 1)        {            trackStack.push(x);            return;        }           // If current element is greater than        // the top element of track stack, push        // the current element to track stack        // otherwise push the element at top of        // track stack again into it.        if (x > trackStack[trackStack.length - 1])            trackStack.push(x);        else            trackStack.push(trackStack[trackStack.length - 1]);    }       function getMax()    {        return trackStack[trackStack.length - 1];    }       function pop()    {        mainStack.pop();        trackStack.pop();    }         push(20);    document.write(getMax() + "</br>");    push(10);    document.write(getMax() + "</br>");    push(50);    document.write(getMax());         // This code is contributed by rameshtravel07.</script>
Output:  
20
20
50
Time Complexity : O(1) Auxiliary Complexity : O(n)This article is contributed by Rohit. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
prerna saini
princiraj1992
PranchalKatiyar
19bcs1298
rameshtravel07
surinderdawra388
Stack
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack in Python
Stack Class in Java
Check for Balanced Brackets in an expression (well-formedness) using Stack
Introduction to Data Structures
Stack | Set 2 (Infix to Postfix)
What is Data Structure: Types, Classifications and Applications
Inorder Tree Traversal without Recursion
Program for Tower of Hanoi
Merge Overlapping Intervals
Implement a stack using singly linked list