Find the next greater element in a Circular Array | Set 2 | C # program for the above approach ; Function to find the NGE for the given circular array [ ] arr ; Initialize stack and nge [ ] array ; Initialize nge [ ] array to - 1 ; Traverse the array ; If stack is not empty and current element is greater than top element of the stack ; Assign next greater element for the top element of the stack ; Pop the top element of the stack ; Print the nge [ ] array ; Driver Code ; Function Call
using System ; using System . Collections . Generic ; class GFG { static void printNGE ( int [ ] arr , int n ) { Stack < int > s = new Stack < int > ( ) ; int [ ] nge = new int [ n ] ; int i = 0 ; for ( i = 0 ; i < n ; i ++ ) { nge [ i ] = - 1 ; } i = 0 ; while ( i < 2 * n ) { while ( s . Count != 0 && arr [ i % n ] > arr [ s . Peek ( ) ] ) { nge [ s . Peek ( ) ] = arr [ i % n ] ; s . Pop ( ) ; } s . Push ( i % n ) ; i ++ ; } for ( i = 0 ; i < n ; i ++ ) { Console . Write ( nge [ i ] + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 4 , - 2 , 5 , 8 } ; int N = arr . Length ; printNGE ( arr , N ) ; } }