text: Find minimum changes required in an array for it to contain k distinct elements | C # 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
code: import java . util . * ; class GFG { static int MAX = 100005 ; static int Min_Replace ( int [ ] arr , int n , int k ) { Arrays . sort ( arr ) ; Integer [ ] freq = new Integer [ MAX ] ; Arrays . fill ( freq , 0 ) ; int p = 0 ; freq [ p ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] ) ++ freq [ p ] ; else ++ freq [ ++ p ] ; } Arrays . sort ( freq , Collections . reverseOrder ( ) ) ; int ans = 0 ; for ( int i = k ; i <= p ; i ++ ) ans += freq [ i ] ; return ans ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 7 , 8 , 2 , 3 , 2 , 3 } ; int n = arr . length ; int k = 2 ; System . out . println ( Min_Replace ( arr , n , k ) ) ; } }