text: Find minimum changes required in an array for it to contain k distinct elements | CPP program to minimum changes required in an array for k distinct elements . ; Function to minimum changes required in an array for k distinct elements . ; Store the frequency of each element ; Store the frequency of elements ; Sort frequencies in descending order ; To store the required answer ; Return the required answer ; Driver code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX  100005 NEW_LINE int Min_Replace ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; int freq [ MAX ] ; memset ( freq , 0 , sizeof freq ) ; int p = 0 ; freq [ p ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] ) ++ freq [ p ] ; else ++ freq [ ++ p ] ; } sort ( freq , freq + n , greater < int > ( ) ) ; int ans = 0 ; for ( int i = k ; i <= p ; i ++ ) ans += freq [ i ] ; return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 7 , 8 , 2 , 3 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; cout << Min_Replace ( arr , n , k ) ; return 0 ; }