What is problem with this greedy algorithm? I have taken care of cases like string = 2399, b = 2


#1

Its giving failing for large test cases.
int counting(string a, auto &maxi){
int count = 0;
auto it = a.begin();
while(it < a.end()){
if(*it == *maxi)
count++;
it++;
}
return count;
}

string solve(string a, int b)
{
int n = a.size();
if(n == 0)return “”;
if(b >= n-1){
sort(a.rbegin(), a.rend());
return a;
}
int i = 0;
string res = “”;
while(b && i < n){
auto maxi = max_element(a.rbegin(), a.rend());
res += *maxi;
if(*maxi != *a.begin()){
int count = min(b, counting(a, maxi));
sort(a.begin(), a.begin()+count);
swap(*a.begin(), *maxi);
b–;
}
a.erase(a.begin());
i++;
}
return res+a;
}