<p>The <strong>beauty</strong> of a string is the difference in frequencies between the most frequent and least frequent characters.</p>

<ul>
	<li>For example, the beauty of <code>&quot;abaacc&quot;</code> is <code>3 - 1 = 2</code>.</li>
</ul>

<p>Given a string <code>s</code>, return <em>the sum of <strong>beauty</strong> of all of its substrings.</em></p>

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

<pre>
<strong>Input:</strong> s = &quot;aabcb&quot;
<strong>Output:</strong> 5
<strong>Explanation: </strong>The substrings with non-zero beauty are [&quot;aab&quot;,&quot;aabc&quot;,&quot;aabcb&quot;,&quot;abcb&quot;,&quot;bcb&quot;], each with beauty equal to 1.</pre>

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

<pre>
<strong>Input:</strong> s = &quot;aabcbaa&quot;
<strong>Output:</strong> 17
</pre>

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

<ul>
	<li><code>1 &lt;= s.length &lt;=<sup> </sup>500</code></li>
	<li><code>s</code> consists of only lowercase English letters.</li>
</ul>

class Solution:
    def beautySum(self, s: str) -> int:
        l = len(s)
        res = 0
        for i in range(l):
            res += self.beautySumSubstr(s, i)
        return res

    def beautySumSubstr(self, s: str, index: int) -> int:
        most = 0
        least = 0
        count = [0] * 26
        count_count = [26]
        res = 0
        l = len(s)
        for i in range(index, l):
            pos = ord(s[i]) - ord('a')
            if count[pos] + 1 >= len(count_count):
                count_count.append(0)

            count_count[count[pos]] -= 1
            count_count[count[pos] + 1] += 1
            
            if count[pos] == 0:
                least = 1
            elif least == count[pos] and count_count[count[pos]] == 0:
                least += 1
            
            count[pos] += 1
            if count[pos] > most:
                most = count[pos]
            
            res += most - least
            # print(f'{i} {least} {most}')
        return res
544