Same problem with monotone fliping coin.
the machanics is like this, if you encounter b in side some a, you need to flip it, so you store the times you encounter the b.
but if you find out what if the whole array is b, or a, or a or b is monopoly in this array.
we assume the now we need to make the whole array to be b. so, every time you meet a, you add the fliping times by 1.
And you also count the occurence of b, if the occurence of b smaller than the b, you reset the flip, because you know in this prefix a shows up more than b, turn b to a is cost minmum, so reset the flip.
the flip is just like a flag standing in the postion j that the last b show up and tells you that from this to the i (s[i] = b), there are fliping times of occurrence of a.
as i sad the flip is like a flag only stands at the b's position, if after the last b, there are no more b, we would increment the flip as these all a is invalid.
class Solution {
public:
int minimumDeletions(string s) {
int bcount =0, flip = 0;
for(int i = 0; i < s.length(); i++){
if(s[i] == 'b'){
bcount++;
}else{
flip++;
}
flip = min(flip, bcount);
}
return flip;
}
};