I am invited to write a function that finds the maximum variable sum of digits in a given number and a given number of digits. For example, the number 81010 has a 3 variable sum with a length of 3 - (8-1 + 0), (1-0 + 1), (0-1 + 0), and we must return the answer 7.
It is easy to summarize each subsequence of numbers, but this can take some time, and the algorithm must be fast enough to deal with very large numbers. I don’t know how to write such a function with runs faster than trivial ...
Iv'e a hint that says that by setting the sum of the first n digits, we can effectively find the sum of the digits, starting with the second digit in the sequence.
Please help, thanks.
PS I saw some question about finding the largest amount, but could not answer the search for the largest variable amount.
What is the code to find the largest sum of consecutive digits:
def max_sum(n,d):
number = list(map(int,str(n)))
maximum = current = sum(number[:d])
for i in range(0, len(number)-d):
current = current - number[i] + number[i+d]
if current > maximum:
maximum = current
return maximum
source
share