Tracking current Maximum Element in a Stack | C # 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 , push the current element to track stack otherwise push the element at top of track stack again into it . ; Driver code
using System ; using System . Collections . Generic ; class GfG { public class StackWithMax { static Stack < int > mainStack = new Stack < int > ( ) ; static Stack < int > trackStack = new Stack < int > ( ) ; public void push ( int x ) { mainStack . Push ( x ) ; if ( mainStack . Count == 1 ) { trackStack . Push ( x ) ; return ; } 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 ( ) ; } } ; public 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 ( ) ) ; } }