Tracking current Maximum Element in a Stack | Python3 program to keep track of maximum element in a stack ; main stack ; tack to keep track of max element ; 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 . ; Driver Code
class StackWithMax : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . mainStack = [ ] NEW_LINE self . trackStack = [ ] NEW_LINE DEDENT def push ( self , x ) : NEW_LINE INDENT self . mainStack . append ( x ) NEW_LINE if ( len ( self . mainStack ) == 1 ) : NEW_LINE INDENT self . trackStack . append ( x ) NEW_LINE return NEW_LINE DEDENT if ( x > self . trackStack [ - 1 ] ) : NEW_LINE INDENT self . trackStack . append ( x ) NEW_LINE DEDENT else : NEW_LINE INDENT self . trackStack . append ( self . trackStack [ - 1 ] ) NEW_LINE DEDENT DEDENT def getMax ( self ) : NEW_LINE INDENT return self . trackStack [ - 1 ] NEW_LINE DEDENT def pop ( self ) : NEW_LINE INDENT self . mainStack . pop ( ) NEW_LINE self . trackStack . pop ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = StackWithMax ( ) NEW_LINE s . push ( 20 ) NEW_LINE print ( s . getMax ( ) ) NEW_LINE s . push ( 10 ) NEW_LINE print ( s . getMax ( ) ) NEW_LINE s . push ( 50 ) NEW_LINE print ( s . getMax ( ) ) NEW_LINE DEDENT