Count array elements with rank not exceeding K | Function to find count of array elements with rank less than or equal to k ; Initialize rank and position ; Sort the given array ; Traverse array from right to left ; Update rank with position , if adjacent elements are unequal ; Return position - 1 , if rank greater than k ; Increase position ; Given array ; Given K ; Function Call
function rankLessThanK ( arr , k , n ) { let rank = 1 ; let position = 1 ; arr . sort ( ) ; for ( let i = n - 1 ; i >= 0 ; i -- ) { if ( i == n - 1 arr [ i ] != arr [ i + 1 ] ) { rank = position ; if ( rank > k ) return position - 1 ; } position ++ ; } return n ; } let arr = [ 2 , 2 , 3 , 4 , 5 ] ; let N = arr . length ; let K = 4 ; document . write ( rankLessThanK ( arr , K , N ) ) ;