Minimum number of distinct elements present in a K | Java program for the above approach ; Function to count the minimum number of distinct elements present in any subsequence of length K of the given array ; Stores the frequency of each array element ; Traverse the array ; Update frequency of array elements ; Store the required result ; Store the length of the required subsequence ; Store the frequencies in decreasing order ; Traverse the map ; Push the frequencies into the HashMap ; Sort the array in decreasing order ; Add the elements into the subsequence starting from one with highest frequency ; If length of subsequence is >= k ; Print the result ; Driver code ; Store the size of the array ; Function Call to count minimum number of distinct elmeents present in a K - length subsequence
import java . util . * ; class GFG { static void findMinimumDistinct ( int A [ ] , int N , int K ) { Map < Integer , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) mp . put ( A [ i ] , mp . getOrDefault ( A [ i ] , 0 ) + 1 ) ; int count = 0 ; int len = 0 ; ArrayList < Integer > counts = new ArrayList < > ( ) ; for ( Map . Entry < Integer , Integer > i : mp . entrySet ( ) ) counts . add ( i . getValue ( ) ) ; Collections . sort ( counts , ( a , b ) -> b - a ) ; for ( int i = 0 ; i < counts . size ( ) ; i ++ ) { if ( len >= K ) break ; len += counts . get ( i ) ; count ++ ; } System . out . print ( count ) ; } public static void main ( String [ ] args ) { int A [ ] = { 3 , 1 , 3 , 2 , 3 , 4 , 5 , 4 } ; int K = 4 ; int N = A . length ; findMinimumDistinct ( A , N , K ) ; } }