HackerEarth Monk and chocolates

Guys,
Can someone explain the approach to solve this. I understand that we need to count the frequency of each character.But after that I cant figure out a way to arrive at the longest substring. Do I perform flips only near characters with highest frequency??? Kindly help out.

This Q has been asked recently, try to search once. If that old answer doesnt clarify, we will help.

hey thanks for replying. I saw your solution, I noticed that you considered only lowercase characters.What about uppercase characters??

It wasnt my solution, it was a reference solution. When you look at complete code (the link is given as a comment if i recall correctly) you will see that EXACT same loop was copy pasted, just limits were changed so it runs on uppercase letters.

//