Maximize frequency sum of K chosen characters from given string | Java program for the above approach ; Function to find the maximum sum of frequencies of the exactly K chosen characters from the String S ; Stores the resultant maximum sum ; Stores the frequency of array elements ; Find the frequency of character ; Sort the frequency array in the descending order ; Iterate to choose K elements greedily ; If the freq [ i ] cards are chosen ; K cards have been picked ; Return the resultant sum ; Driver Code
import java . util . * ; class GFG { static int maximumSum ( String S , int N , int K ) { int sum = 0 ; Integer [ ] freq = new Integer [ 256 ] ; Arrays . fill ( freq , 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { freq [ ( int ) S . charAt ( i ) ] += 1 ; } Arrays . sort ( freq , Collections . reverseOrder ( ) ) ; for ( int i = 0 ; i < 256 ; i ++ ) { if ( K > freq [ i ] ) { sum += freq [ i ] * freq [ i ] ; K -= freq [ i ] ; } else { sum += freq [ i ] * K ; break ; } } return sum ; } public static void main ( String args [ ] ) { String S = " GEEKSFORGEEKS " ; int K = 10 ; int N = S . length ( ) ; System . out . print ( maximumSum ( S , N , K ) ) ; } }