I had an idea!
Since you only need to count substrings, you don't care what they really are. So instead, you can just save the number of possible amounts.
Then, what if you had a function that could combine the counter tables of two tweaks and give you counts of their combinations?
And since I know this was a terrible explanation, I will give an example. Say that you are assigned a number:
2493
Divide it in half and continue the division until you get individual numbers:
2493 / \ 24 93 /\ /\ 2 4 9 3
What can 2 summarize? Easy: 2 . And 4 can only stack up to 4 . You can build tables of how many substrings are added to each value (mod 9):
0 1 2 3 4 5 6 7 8 2: 0 0 1 0 0 0 0 0 0 4: 0 0 0 0 1 0 0 0 0 9: 1 0 0 0 0 0 0 0 0 3: 0 0 0 1 0 0 0 0 0
Simple joining of two tables. Add the first table, the second table and each combination of the two modes 9 (for the first combination this is equivalent to 2 , 4 and 24 ; for the second, 9 , 3 and 93 ):
0 1 2 3 4 5 6 7 8 24: 0 0 1 0 1 0 1 0 0 93: 1 0 0 2 0 0 0 0 0
Then do it again:
0 1 2 3 4 5 6 7 8 2493: 3 0 2 2 2 2 2 2 0
And here is your answer, sitting in column 0 : 3 . This corresponds to substrings 243 , 2493 and 9 . You do not know this, though, because you just saved the score - and, fortunately, you don't care!
After implementation, this will give you O(n) performance - you just need to figure out how to join tables in O(1) . But hey is homework, isn't it? Good luck