Maximize frequency sum of K chosen characters from given string | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSum ( string S , int N , int K ) { int sum = 0 ; int freq [ 256 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { freq [ int ( S [ i ] ) ] ++ ; } sort ( freq , freq + 256 , greater < int > ( ) ) ; 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 ; } int main ( ) { string S = " GEEKSFORGEEKS " ; int K = 10 ; int N = S . length ( ) ; cout << maximumSum ( S , N , K ) ; return 0 ; }