Find minimum changes required in an array for it to contain k distinct elements | Python 3 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
MAX = 100005 NEW_LINE def Min_Replace ( arr , n , k ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE freq = [ 0 for i in range ( MAX ) ] NEW_LINE p = 0 NEW_LINE freq [ p ] = 1 NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i - 1 ] ) : NEW_LINE INDENT freq [ p ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT p += 1 NEW_LINE freq [ p ] += 1 NEW_LINE DEDENT DEDENT freq . sort ( reverse = True ) NEW_LINE ans = 0 NEW_LINE for i in range ( k , p + 1 , 1 ) : NEW_LINE INDENT ans += freq [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 7 , 8 , 2 , 3 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE print ( Min_Replace ( arr , n , k ) ) NEW_LINE DEDENT