# Sum of Beauty of All Substrings

# 1781. Sum of Beauty of All Substrings

The beauty of a string is the difference in frequencies between the most frequent and least frequent characters.

For example, the beauty of “abaacc” is 3 – 1 = 2.
Given a string s, return the sum of beauty of all of its substrings.

```### Example 1:
```
Input: s = "aabcb"
Output: 5
Explanation: The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with beauty equal to 1.
```
```
```### Example 2:
```
Input: s = "aabcbaa"
Output: 17
```
```
```Constraints:
```
1 <= s.length <= 500
s consists of only lowercase English letters.
```
```
```/**
* @param {string} s
* @return {number}
*/
var beautySum = function(s) {
const len = s.length;
const freq = new Array(26).fill(0);
let out = 0;

for(let i = 0; i < len; i++) {
freq[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++;
for(let j = i + 1; j < len; j++) {
freq[s[j].charCodeAt(0) - 'a'.charCodeAt(0)]++;
out += minMaxDiff(freq);
}
freq.fill(0);
}

function minMaxDiff(letterFreq) {
letterFreq = letterFreq.filter(f => f);
return Math.max(...letterFreq) - Math.min(...letterFreq);
}

return out;
};

```