<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:
        n = len(s)
        ans = 0
        for i in range(n):
            h,l = None,None
            counter = [0]*26
            lLetter = None
            for j in range(i,n):
                index = ord(s[j])-ord('a')
                counter[index] += 1
                if (not h or h<counter[index]):
                    h = counter[index]
                l = float('inf')
                for ele in counter:
                    if (ele!=0):
                        l = min(l,ele)
                # if (not l or l>=counter[index] or lLetter==index):
                    
                #     l = counter[index]
                #     # print('in',index,counter[index])
                #     lLetter = index
                # print(i,j,h,l,chr(ord('a')+lLetter))
                ans += h-l
        return ans

























        # d = dict()
        # ans = 0
        # n = len(s)
        # for i in range(n):
        #     d = {s[i]:1}
        #     h = 1
        #     l,xl,length = 1,set([s[i]]),1
        #     for j in range(i+1,n):
        #         try:
        #             d[s[j]] += 1
        #         except:
        #             d[s[j]] = 1
        #         h = max(h,d[s[j]])
        #         if (l==d[s[j]]):
        #             if (s[j] not in xl):
        #                 xl.add(s[j])
        #                 length += 1
        #         elif (l>d[s[j]]):
        #             xl = set([s[j]])
        #             l = d[s[j]]
        #             length = 1
        #         else:
        #             if (s[j] in xl):
        #                 xl.remove(s[j])
        #                 length -= 1
        #             if (length==0):
        #                 xl.add(s[j])
        #                 length += 1
        #                 l = d[s[j]]
        #         # print(h,l)
        #         ans += h-l
        # return ans
3704