<p>You are given a string <code>s</code> consisting only of characters <code>&#39;a&#39;</code> and <code>&#39;b&#39;</code>​​​​.</p>

<p>You can delete any number of characters in <code>s</code> to make <code>s</code> <strong>balanced</strong>. <code>s</code> is <strong>balanced</strong> if there is no pair of indices <code>(i,j)</code> such that <code>i &lt; j</code> and <code>s[i] = &#39;b&#39;</code> and <code>s[j]= &#39;a&#39;</code>.</p>

<p>Return <em>the <strong>minimum</strong> number of deletions needed to make </em><code>s</code><em> <strong>balanced</strong></em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;aababbab&quot;
<strong>Output:</strong> 2
<strong>Explanation:</strong> You can either:
Delete the characters at 0-indexed positions 2 and 6 (&quot;aa<u>b</u>abb<u>a</u>b&quot; -&gt; &quot;aaabbb&quot;), or
Delete the characters at 0-indexed positions 3 and 6 (&quot;aab<u>a</u>bb<u>a</u>b&quot; -&gt; &quot;aabbbb&quot;).
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;bbaaaaabb&quot;
<strong>Output:</strong> 2
<strong>Explanation:</strong> The only solution is to delete the first two characters.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>
	<li><code>s[i]</code> is&nbsp;<code>&#39;a&#39;</code> or <code>&#39;b&#39;</code>​​.</li>
</ul>

class Solution:
    def minimumDeletions(self, s: str) -> int:
        # balanced string means b cannot occur before a
        # so much be aaa...bbb...
        # a's all together and b's all together
        # how many deletes do we need?
        # can we be greedy here? delete as we see excess b's at the front
        # no, consider: abbbbbba, need to delete a's instead
        # binary serach on solution? a bit slow
        # recursive: subproblems: either delete curr or keep curr
        # if we see an A, must delete all b's before this
        # maybe can consider all split points
        # if we split at index i for example, we know that we must delete all b's before i and delete all a's after i
        # count all b's before all i's and all a's after all i's
        # pre compute this, then loop all i's
        a_count = [0]*(len(s)+1)
        b_count = [0]*(len(s)+1)
        curr_a, curr_b = 0, 0
        # index 0 means count of a's before index 0 not including
        # index 6 means count of a's before index 6 not including
        # index 7 (last)
        for i in range(len(s)):
            b_count[i] = curr_b
            curr_b += s[i] == 'b'
        b_count[-1] = curr_b
        for j in range(len(s)-1,-1,-1):
            curr_a += s[j] == 'a'
            a_count[j] = curr_a
        res = float('inf')
        for k in range(len(s)+1):
            res = min(res, b_count[k]+a_count[k])
        return res

25288