Find minimum changes required in an array for it to contain k distinct elements | Javascript 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
var MAX = 100005 ; function Min_Replace ( arr , n , k ) { arr . sort ( ( a , b ) => a - b ) var freq = Array ( MAX ) . fill ( 0 ) ; var p = 0 ; freq [ p ] = 1 ; for ( var i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] ) ++ freq [ p ] ; else ++ freq [ ++ p ] ; } freq . sort ( ( a , b ) => b - a ) ; var ans = 0 ; for ( var i = k ; i <= p ; i ++ ) ans += freq [ i ] ; return ans ; } var arr = [ 1 , 2 , 7 , 8 , 2 , 3 , 2 , 3 ] ; var n = arr . length ; var k = 2 ; document . write ( Min_Replace ( arr , n , k ) ) ;