In this problme we need to removal character from string aab...bab containing only a and b, and make sure in the end it becomes aa..aab...b, find the minimum removal.
I tried to count the prefix for how many b presents, and postifx for how many a presents, then when we want to seperate the string into two clusters, [.. idx] and [idx+1 ..], and make the first clsuter all a, and the second all b, we only need to add up prefBandpostA`. we check and maintan the best answer.
Code
class Solution {
public:
int minimumDeletions(string s) {
int n = s.size();
vector<int> prefB(n);
vector<int> postA(n);
int cntB = 0;
for(int i = 0 ; i < n ; ++i) {
if(s[i] == 'b') ++cntB;
prefB[i] = cntB;
}
int cntA = 0;
for(int i = n-1 ; i >= 0 ; --i) {
if(s[i] == 'a') ++cntA;
postA[i] = cntA;
}
int minRemoval = n;
for(int i = -1 ; i < n ; ++i) {
// [.. i] contains all A
// [i+1 ..] contains all B
int removal = (i >= 0 ? prefB[i] : 0) + (i < n-1 ? postA[i+1] : 0);
minRemoval = min(minRemoval, removal);
}
return minRemoval;
}
};