Find relative rank of each element in array | C ++ program for 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findRank ( int A [ ] , int N ) { int rank [ N ] = { } ; stack < int > s ; s . push ( A [ N - 1 ] ) ; for ( int i = N - 2 ; i >= 0 ; i -- ) { if ( A [ i ] < s . top ( ) ) { s . push ( A [ i ] ) ; rank [ i ] = s . size ( ) - 1 ; } else { while ( ! s . empty ( ) && A [ i ] >= s . top ( ) ) { s . pop ( ) ; } s . push ( A [ i ] ) ; rank [ i ] = s . size ( ) - 1 ; } } for ( int i = 0 ; i < N ; i ++ ) { cout << rank [ i ] << " ▁ " ; } } int main ( ) { int A [ ] = { 1 , 2 , 3 , 5 , 4 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; findRank ( A , N ) ; return 0 ; }