Find relative rank of each element in array | C # program to implement the above approach ; Function to find relative rank for each element in the array A [ ] ; Create Rank Array ; Stack to store numbers in non - decreasing order from right ; Push last element in stack ; Iterate from second last element to first element ; If current element is less than the top of stack and push A [ i ] in stack ; Rank is stack size - 1 for current element ; Pop elements from stack till current element is greater than the top ; Push current element in Stack ; Rank is stack size - 1 ; Print rank of all elements ; Driver Code ; Given array A [ ] ; Function call
using System ; using System . Collections . Generic ; using System . Linq ; class GFG { static void findRank ( int [ ] A , int N ) { int [ ] rank = new int [ N ] ; Stack < int > s = new Stack < int > ( ) ; s . Push ( A [ N - 1 ] ) ; for ( int i = N - 2 ; i >= 0 ; i -- ) { if ( A [ i ] < s . Peek ( ) ) { s . Push ( A [ i ] ) ; rank [ i ] = s . Count ( ) - 1 ; } else { while ( s . Count ( ) != 0 && A [ i ] >= s . Peek ( ) ) { s . Pop ( ) ; } s . Push ( A [ i ] ) ; rank [ i ] = s . Count ( ) - 1 ; } } for ( int i = 0 ; i < N ; i ++ ) { Console . Write ( rank [ i ] + " ▁ " ) ; } } public static void Main ( ) { int [ ] A = new int [ ] { 1 , 2 , 3 , 5 , 4 } ; int N = A . Length ; findRank ( A , N ) ; } }