All problems

Problem 713

Sum of Beauty of All Substrings

Medium · 20 pts · String, Hash Table, Counting

Problem

The beauty of a string is the frequency of its most frequent character minus the frequency of its least frequent character, counting only characters that appear in it. For example, the beauty of abaacc is 3 - 1 = 2. Find the sum of the beauties of all non-empty substrings of S (substrings at different positions count separately). For each start, extend the end one character at a time while updating the 26 letter counts.

Input

A single string S of lowercase English letters.

Output

Print the sum of beauties of all substrings.

Constraints

1 <= |S| <= 500

Example input

aabcb

Example output

5

Explanation

For aabcb, the substrings with non-zero beauty are aab, aabc, abcb, bcb and aabcb, each with beauty 1. All others have beauty 0, so the sum is 5.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Maximum Nesting Depth of the Parentheses Next: Repeated String Match