Previous greater element | C # program previous greater element An efficient solution to print previous greater element for every element in an array . ; Create a stack and push index of first element to it ; Previous greater for first element is always - 1. ; Traverse remaining elements ; Pop elements from stack while stack is not empty and top of stack is smaller than arr [ i ] . We always have elements in decreasing order in a stack . ; If stack becomes empty , then no element is greater on left side . Else top of stack is previous greater . ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static void prevGreater ( int [ ] arr , int n ) { Stack < int > s = new Stack < int > ( ) ; s . Push ( arr [ 0 ] ) ; Console . Write ( " - 1 , ▁ " ) ; for ( int i = 1 ; i < n ; i ++ ) { while ( s . Count != 0 && s . Peek ( ) < arr [ i ] ) s . Pop ( ) ; if ( s . Count == 0 ) Console . Write ( " - 1 , ▁ " ) ; else Console . Write ( s . Peek ( ) + " , ▁ " ) ; s . Push ( arr [ i ] ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 10 , 4 , 2 , 20 , 40 , 12 , 30 } ; int n = arr . Length ; prevGreater ( arr , n ) ; } }