Find the next greater element in a Circular Array | Set 2 | Java 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
import java . util . * ; class GFG { static void printNGE ( int arr [ ] , int n ) { Stack < Integer > s = new Stack < > ( ) ; 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 . isEmpty ( ) && 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 ++ ) { System . out . print ( nge [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 4 , - 2 , 5 , 8 } ; int N = arr . length ; printNGE ( arr , N ) ; } }