Problem 540
Minimum Deletions to Make String Balanced
Medium · 20 pts · String, Dynamic Programming, Stack
Problem
You are given a string of the letters a and b. The string is balanced if no b appears anywhere before an a, which means it looks like some a's followed by some b's. Find the minimum number of characters to delete to make it balanced. Scan from left to right, counting the b's seen so far; at each a, either delete this a (one more deletion) or delete every b seen so far, whichever is cheaper.
Input
A single string S made of the letters a and b.
Output
Print the minimum number of deletions.
Constraints
1 <= |S| <= 100000
Example input
aababbab
Example output
2
Explanation
In aababbab, deleting the b at index 2 and the a at index 6 leaves aaabbb, which is balanced. One deletion is not enough, so the answer is 2.