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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printNGE ( int * arr , int n ) { stack < int > s ; int nge [ n ] , i = 0 ; for ( i = 0 ; i < n ; i ++ ) { nge [ i ] = -1 ; } i = 0 ; while ( i < 2 * n ) { while ( ! s . empty ( ) && arr [ i % n ] > arr [ s . top ( ) ] ) { nge [ s . top ( ) ] = arr [ i % n ] ; s . pop ( ) ; } s . push ( i % n ) ; i ++ ; } for ( i = 0 ; i < n ; i ++ ) { cout << nge [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 4 , -2 , 5 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printNGE ( arr , N ) ; return 0 ; }