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
using System ; using System . Collections . Generic ; class GFG { static int min_elements ( int [ ] arr , int N , int K ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . ContainsKey ( arr [ i ] ) ) { mp [ arr [ i ] ] = mp [ arr [ i ] ] + 1 ; } else { mp . Add ( arr [ i ] , 1 ) ; } } List < int > Freq = new List < int > ( ) ; foreach ( KeyValuePair < int , int > it in mp ) { int i = it . Key ; Freq . Add ( mp [ i ] ) ; } Freq . Sort ( ) ; Freq . Reverse ( ) ; int len = Freq . Count ; if ( len <= K ) { return 0 ; } int cntMin = 0 ; for ( int i = K ; i < len ; i ++ ) { cntMin += Freq [ i ] ; } return cntMin ; } public static void Main ( String [ ] args ) { int [ ] arr = { 5 , 1 , 3 , 2 , 4 , 1 , 1 , 2 , 3 , 4 } ; int N = arr . Length ; int K = 3 ; Console . Write ( min_elements ( arr , N , K ) ) ; } }