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.
Example 1:
Input: s = "aababbab" Output: 2 Explanation: You can either: Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb").
The problem can be formulated as DP.
At every point when you see 'a' , you have 2 options,
- remove all the b's you found earlier. --> total cost = count_of_b
OR - delete the current 'a'. --> total cost = cur_total_cost + 1
If u see a 'b' , then no more cost.
Thus maintain the count of 'b's you found.
class Solution:
def minimumDeletions(self, s: str) -> int:
cnt_b = 0
dp = 0
for c in s:
if c == 'b':
cnt_b += 1
else:
dp = min(cnt_b, dp+1)
return dp