<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:
        chars = set()
        dic = {}
        for ele in s:
            chars.add(ele)
        
        for ele in chars:
            pre_count = [0]*(len(s)+1)
            for i in range(len(s)):
                if s[i]==ele:
                    pre_count[i+1] = 1
            for i in range(1,len(s)+1):
                pre_count[i] = pre_count[i-1]+pre_count[i]
            dic[ele] = pre_count
        res = 0
        
        for l in range(len(s)-1):
            for r in range(l+1,len(s)):
                max_freq, min_freq = 0, len(s)
                for ele in chars:
                    max_freq = max(max_freq, dic[ele][r+1]-dic[ele][l])
                    if dic[ele][r+1]-dic[ele][l]:
                        min_freq = min(min_freq, dic[ele][r+1]-dic[ele][l])
               
                if min_freq:
                    # print(l,r,max_freq,min_freq)
                    res+=max_freq-min_freq
        
        return res



        
        print(dic)
        return 0



        
12253