Count array elements with rank not exceeding K | C ++ program for the above approach ; 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 ; Driver Code ; Given array ; Given K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int rankLessThanK ( int * arr , int k , int n ) { int rank = 1 ; int position = 1 ; sort ( arr , arr + n ) ; for ( int 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 ; } int main ( ) { int arr [ 5 ] = { 2 , 2 , 3 , 4 , 5 } ; int N = 5 ; int K = 4 ; cout << rankLessThanK ( arr , K , N ) ; return 0 ; }