String of has n cards is given. Each card has an uppercase letter written on it. Geek must choose k cards from given cards. The some coins are given to geek depending on the chosen cards. Formally, for each card chosen i . number of coins provided is equal to cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins provided to geek.
Your task is to calculate maximum number of coins that geek can get.
Example :
Input : n=15,k= 10 str[]="DZFDFZDFDDDDDDF" Output : 82 Explanation : geek can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin 9*9+1=82 Input : n=6,k= 2 str[]=MJDIJJ Output : 4 Explanation : Geek will take two cards with letter J therefore 2*2=4
Approach :
It is clear that this total score is (the number of ‘A’ in K cards)^2 + (the number of ‘B’ in K cards)^2 + … + (the number of ‘Z’ in K cards)^2 This value will be maximized by the simple greedy algorithm, take K cards from most appeared character in N cards, the second most appeared character in N cards, and so on.
- Make a frequency array to count frequency of letters in string
- Sort frequency array in non-increasing order
- count number of cards from frequency and multiply ans by their respected frequency till k cards is selected
Implementation :
// C++ code for above approach
#include <bits/stdc++.h>
using namespace std;
// Frequency array to store frequency of letters in string
long long fre[26];
// Function to calculate coins
int countCoins(int n, int k, string s)
{
// ans will store number of coins
int ans = 0;
for (int i = 0; i < s.length(); i++) {
int u = s[i] - 'A';
fre[u]++;
}
// Sorting frequency array in non-decreasing order
sort(fre, fre + 26, greater<int>());
for (int i = 0; i < 26; i++) {
if (k >= fre[i]) {
ans += (fre[i] * fre[i]);
k -= fre[i];
}
else {
ans += (k * k);
break;
}
}
return ans;
}
int main()
{
int n = 6, k = 2;
string str = "MJDIJJ";
cout << countCoins(n, k, str);
return 0;
}
Time Complexity : O(nlogn)
Space Complexity : O(n)