class Solution {
public:
int maximumGain(string s, int x, int y) {
int n = s.size();
int points = 0;
// A pair is made up of a major and minor letter. The first letter is the major and the second letter is the minor.
// If y > x, then the pairs to reap first are "ba", because "ba" will be worth more than "ab".
char major= (y > x) ? 'b' : 'a';
char minor = (y > x) ? 'a' : 'b';
int large = (y > x) ? y : x;
int small = (y > x) ? x : y;
// majorCount is the number of times the major letter has been seen so far. Decrease this value
// every time the minor letter is found. This means a major pair, (major, minor), has been found
// and one of the major letters was used up, so decrease majorCount.
// If a minor letter is encountered when majorCount is zero, then increase the minorCount.
// Use up these minor pairs at the end. If at the end of this iteration, there is a minorCount
// and a majorCount, then those are the minor pairs. They are the cases where a minor letter was found
// before a major letter was found.
int majorCount = 0;
int minorCount = 0;
for(int ii=0; ii<n; ++ii)
{
// If the character is not an 'a' or 'b', then start all the counts over at zero.
// Pairs can't be made across these non 'a''b' barriers.
// Do increase the count by the number of minor pairs.
if (s[ii] != major && s[ii] != minor)
{
points += (std::min(majorCount, minorCount)) * small;
majorCount = 0;
minorCount = 0;
continue;
}
if(s[ii] == major)
{
++majorCount;
}
else if (majorCount > 0)
{
points += large;
--majorCount;
}
else
{
++minorCount;
}
}
points += (std::min(majorCount, minorCount)) * small;
return points;
}
};