<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:
        # print(s[1:])
        # print(s[:-1])
        fq = [0] * 26

        for ch in s:
            i = ord(ch) - ord('a')
            fq[i] += 1
    
        r=0
        visited = set()
        def calcBeauty(si, fq):
            # print(si, s[si[0]:si[1]])
            nonlocal visited, r

            if si[1] > si[0] and si not in visited:
                beauty = max(fq) - min([x for x in fq if x > 0])
                r += beauty
                visited.add(si)
                # print(s, beauty)
                
                lfq = fq[::]
                lfq[ord(s[si[0]]) - ord('a')] -= 1
                lbeauty = calcBeauty((si[0]+1, si[1]), lfq)
                
                rfq = fq[::]
                rfq[ord(s[si[1]]) - ord('a')] -= 1
                rbeauty = calcBeauty((si[0], si[1]-1), rfq)

        calcBeauty((0, len(s)-1), fq)

        return r


3890