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
function min_elements ( arr , N , K ) { let mp = new Map ( ) ; for ( let i = 0 ; i < N ; i ++ ) { if ( mp . has ( arr [ i ] ) ) { mp . set ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) } else { mp . set ( arr [ i ] , 1 ) } } let Freq = [ ] ; for ( let it of mp ) { let i = it [ 0 ] ; Freq . push ( mp . get ( i ) ) ; } Freq . sort ( ( a , b ) => b - a ) ; let len = Freq . length ; if ( len <= K ) { return 0 ; } let cntMin = 0 ; for ( let i = K ; i < len ; i ++ ) { cntMin += Freq [ i ] ; } return cntMin ; } let arr = [ 5 , 1 , 3 , 2 , 4 , 1 , 1 , 2 , 3 , 4 ] ; let N = arr . length ; let K = 3 ; document . write ( min_elements ( arr , N , K ) ) ;