<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:
        def f(s1):
            d={}
            for c in s1:
                d[c]=d.get(c,0)+1
            l=sorted(d.values())
            return l[-1]-l[0]

        val=0
        cnt=0
        for i in range(len(s)):
            for j in range(i,len(s)):
                val=f(s[i:j+1])
                cnt+=val
        return cnt

        




















        # def f(s1):
        #     d={}
        #     for c in s1:
        #         d[c]=d.get(c,0)+1
        #     l=sorted(d.values())
        #     return l[-1]-l[0]

        # cnt=0
        # for i in range(len(s)):
        #     for j in range(i,len(s)):
        #         val=f(s[i:j+1])
        #         cnt+=val
        # return cnt



        # def calculate_beauty(s1):
        #     char_count = {}
        #     for c in s1:
        #         char_count[c] = char_count.get(c, 0) + 1
        #     sorted_counts = sorted(char_count.values())
        #     return sorted_counts[-1] - sorted_counts[0]

        # total_beauty = 0
        # beauty_cache = {}

        # for i in range(len(s)):
        #     for j in range(i, len(s)):
        #         if (i, j) not in beauty_cache:
        #             beauty_cache[(i, j)] = calculate_beauty(s[i:j + 1])
        #         total_beauty += beauty_cache[(i, j)]

        # return total_beauty

            
        
13182