Minimum replacements required to have at most K distinct elements in the array | C ++ program to implement the above approach ; Function to find minimum count of array elements required to be replaced such that count of distinct elements is at most K ; Store the frequency of each distinct element of the array ; Traverse the array ; Update frequency of arr [ i ] ; Store frequency of each distinct element of the array ; Traverse the map ; Stores key of the map ; Insert mp [ i ] into Freq [ ] ; Sort Freq [ ] in descending order ; Stores size of Freq [ ] ; If len is less than or equal to K ; Stores minimum count of array elements required to be replaced such that count of distinct elements is at most K ; Iterate over the range [ K , len ] ; Update cntMin ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_elements ( int arr [ ] , int N , int K ) { map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ arr [ i ] ] ++ ; } vector < int > Freq ; for ( auto it : mp ) { int i = it . first ; Freq . push_back ( mp [ i ] ) ; } sort ( Freq . rbegin ( ) , Freq . rend ( ) ) ; int len = Freq . size ( ) ; if ( len <= K ) { return 0 ; } int cntMin = 0 ; for ( int i = K ; i < len ; i ++ ) { cntMin += Freq [ i ] ; } return cntMin ; } int main ( ) { int arr [ ] = { 5 , 1 , 3 , 2 , 4 , 1 , 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; cout << min_elements ( arr , N , K ) ; return 0 ; }