This problem needs to aggregate to (num, count) tree map. Always stick to top 2 elements. After processed first element, aggregate the count of first element to second element.

For example, 77744444, orders = 10.

For TreeMap, it has (7, 3), (4, 5)

It can be added to answer by below numbers:

7 7 7 <– e1

6 6 6

5 5 5 <– e2

Orders is 8. All the numbers can be used to add into answer.

For one column, it is 5+6+7. The formula is (e2 – e1 + 1) * (e1 + e2) / 2 = 18

So answer = answer + 18 * 3

After that, tree map becomes to (4, 3), (4, 5). Merging them, it becomes (4, 8). Orders -= 9

Consider case 7774, orders = 8. (7, 3), (4, 1)

Only numbers in red will be added to answer.

In this case, availRow = 8 % 3 = 2. mod = 8 / 3 = 2

One part, (e1 – e2 + 1) * (e1 + e2) / 2 * 3. 3 is the number of column.

Another part, (secondElement.key + 1)*mod = (4 + 1) * mod = 5 * 2 = 10