[LeetCode] Minimum Deletions to Make String Balanced

1653. Minimum Deletions to Make String Balanced

You are given a string s consisting only of characters ‘a’ and ‘b’​​​​.

You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = ‘b’ and s[j]= ‘a’.

Return the minimum number of deletions needed to make s balanced.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int minimumDeletions(string s) {
int n = s.length(), res = INT_MAX;
vector<int> B;
for(int i = 0, a = 0, b = 0; i < n; i++) {
if(s[i] == 'b') b++;
B.push_back(b);
}
for(int i = n - 1, a = 0; i >= 0; i--) {
res = min(res, B[i] + a - (s[i] == 'b'));
if(s[i] == 'a') a++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/30/PS/LeetCode/minimum-deletions-to-make-string-balanced/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.