Input: str = "205"
Output: 57
Explanation: Substrings that can be removed are "2", "0", "5", "20", "05", "205". The resultant strings are "05", "25", "20", "5", "2", "0" respectively. Therefore, the sum will be 57.
Input: str = "1234"
Output: 680
Explanation: Substrings that can be removed are "1", "2", "3", "4", "12", "23", "34", "123", "234", "1234". The resultant strings are "234", "134", "124", "123", "34", "14", "12", "4", "1", "0" respectively. Therefore, the sum will be 680.
Illustration:
Let str = "1234"
All strings possible by removal of non-empty substrings and position of each character in these strings are as follows:
| 100 | 10 | 1 |
234 | 2 | 3 | 4 |
134 | 1 | 3 | 4 |
124 | 1 | 2 | 4 |
123 | 1 | 2 | 3 |
34 | | 3 | 4 |
14 | | 1 | 4 |
12 | | 1 | 2 |
4 | | | 4 |
1 | | | 1 |
0 | | | 0 |
From the above table, get the contribution at every index, for exampleContribution at 1 -> ((1 + 2 + 3) * 1 + 4 * 6) * 1
Contribution at 10 -> ((1 + 2) * 2 + 3 * 3) * 10
Contribution at 100 -> ((1) * 3 + 2 * 1) * 100
Thus, generate a general formula for every index, i.e
Contribution at 10x = (\Sigma(n - x - 2) * (x + 1) + str[n - x - 1] * (n - x - 1)th term of Triangular Number) * 10x