← DiffPush

Sum of beauty of all substrings

Standard Bar Strings · Medium O(n^2) · O(1)

Spread Score Across Every Listening Window

A station manager audits a broadcast day stored as one string of jingle codes. Every contiguous window gets a spread score: the count of the most-repeated jingle inside the window minus the count of the least-repeated one, so windows where everything appears equally score zero. The audit totals the spread over every window of the day.

Input: A string s of lowercase English letters.

Output: The sum of (maximum character frequency minus minimum character frequency) over all substrings of s; substrings with a single distinct character contribute 0.

Constraints

Examples

Example 1

Input: {"s":"aabcb"}
Output: 5
Only "aab", "aabc", "aabcb", "abcb" and "bcb" carry a spread of 1; every other window is single-character or perfectly balanced.

Example 2

Input: {"s":"aabcbaa"}
Output: 17
Longer windows accumulate bigger spreads — the tail windows dominated by a's push the total to 17.

Solve this in your browser →

Also on LeetCode ↗