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.
Solutions
Solution 1: Enumeration + Counting
Thinking
Beauty is the gap between the most and least frequent letters in a substring. \(n\le 500\) allows all \(O(n^2)\) windows.
Fix the left end, extend right while updating a counter, and add \(\max-\min\) each time.
Enumerate the starting position \(i\) of each substring, find all substrings with the character at this starting position as the left endpoint, then calculate the beauty value of each substring, and accumulate it to the answer.
The time complexity is \(O(n^2 \times C)\), and the space complexity is \(O(C)\). Here, \(n\) is the length of the string, and \(C\) is the size of the character set. In this problem, \(C = 26\).
/** * @param {string} s * @return {number} */varbeautySum=function(s){letans=0;for(leti=0;i<s.length;++i){constcnt=newMap();for(letj=i;j<s.length;++j){cnt.set(s[j],(cnt.get(s[j])||0)+1);constt=Array.from(cnt.values());ans+=Math.max(...t)-Math.min(...t);}}returnans;};
Solution 2
Thinking
Solution 1 rescans the counter for min and max. Tracking frequency-of-frequencies plus running \(mi,mx\) updates both ends in \(O(1)\) after each insertion.