Minimum replacements required to have at most K distinct elements in the array | 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
def min_elements ( arr , N , K ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if arr [ i ] in mp : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT Freq = [ ] NEW_LINE for it in mp : NEW_LINE INDENT i = it NEW_LINE Freq . append ( mp [ i ] ) NEW_LINE DEDENT Freq . sort ( ) NEW_LINE Freq . reverse ( ) NEW_LINE Len = len ( Freq ) NEW_LINE if ( Len <= K ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT cntMin = 0 NEW_LINE for i in range ( K , Len ) : NEW_LINE INDENT cntMin += Freq [ i ] NEW_LINE DEDENT return cntMin NEW_LINE DEDENT arr = [ 5 , 1 , 3 , 2 , 4 , 1 , 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 ; NEW_LINE print ( min_elements ( arr , N , K ) ) NEW_LINE