Number of NGEs to the right |  ; use of stl stack in Java ; push the ( n - 1 ) th index to the stack ; traverse in reverse order ; if no element is greater than arr [ i ] the number of NGEs to right is 0 ; number of NGEs to right of arr [ i ] is one greater than the number of NGEs to right of higher number to its right ; reverse again because values are in reverse order ; returns the vector of number of next greater elements to the right of each index . ; Driver code ; query 1 answered ; query 2 answered ; query 3 answered
using System ; using System . Collections . Generic ; public class GFG { static List < int > no_NGN ( int [ ] arr , int n ) { List < int > nxt = new List < int > ( ) ; Stack < int > s = new Stack < int > ( ) ; nxt . Add ( 0 ) ; s . Push ( n - 1 ) ; for ( int i = n - 2 ; i >= 0 ; i -- ) { while ( s . Count != 0 && arr [ i ] >= arr [ s . Peek ( ) ] ) s . Pop ( ) ; if ( s . Count == 0 ) nxt . Add ( 0 ) ; else nxt . Add ( nxt [ n - s . Peek ( ) - 1 ] + 1 ) ; s . Push ( i ) ; } nxt . Reverse ( ) ; return nxt ; } public static void Main ( String [ ] args ) { int n = 8 ; int [ ] arr = { 3 , 4 , 2 , 7 , 5 , 8 , 10 , 6 } ; List < int > nxt = no_NGN ( arr , n ) ; Console . Write ( nxt [ 3 ] + " STRNEWLINE " ) ; Console . Write ( nxt [ 6 ] + " STRNEWLINE " ) ; Console . Write ( nxt [ 1 ] + " STRNEWLINE " ) ; } }