Find relative rank of each element in array | Java 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
import java . io . * ; import java . util . * ; import java . lang . * ; class GFG { static void findRank ( int [ ] A , int N ) { int [ ] rank = new int [ N ] ; Stack < Integer > s = new Stack < Integer > ( ) ; s . add ( A [ N - 1 ] ) ; for ( int i = N - 2 ; i >= 0 ; i -- ) { if ( A [ i ] < s . peek ( ) ) { s . add ( A [ i ] ) ; rank [ i ] = s . size ( ) - 1 ; } else { while ( ! s . isEmpty ( ) && A [ i ] >= s . peek ( ) ) { s . pop ( ) ; } s . add ( A [ i ] ) ; rank [ i ] = s . size ( ) - 1 ; } } for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( rank [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int A [ ] = { 1 , 2 , 3 , 5 , 4 } ; int N = A . length ; findRank ( A , N ) ; } }