简体   繁体   中英

Finding maximum alternating sum of digits (python 3)

I'm asked to write a function which finds the maximum alternating sum of digits in a given number and a given number of digits. For example, the number 81010 has 3 alternating sum with length 3 - (8-1+0),(1-0+1),(0-1+0) and we are supposed to return the answer 7.

It is easy to sum every sub sequence of digits, but it can take a while and the algorithm should be fast enough to deal with very big numbers. I don't know how to write such function with runs faster than the trivial one...

Iv'e a clue which says to think how by given the sum of 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 did saw some question about finding the biggest sum, but couldn't manage to implement the answers for finding the biggest alternating sum.

That's the code for finding the biggest 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
1. Negate every even number (81010 -> 8 -1 0 -1 0), find biggest_sum_1 starting at an odd position
2. Negate every odd number (81010 -> -8 1 0 1 0), find biggest_sum_2 starting at an even position
3. Return max(biggest_sum_1, biggest_sum_2)

You asked for the algorithm, so this should be migrated to the Theoretical Computer Science site.

EDIT: added python code

def max_alt_sum(n,d):
  number = list(map(int,str(n)))
  negatedEven = []
  negatedOdd = []
  for i,v in enumerate(number):
    if i%2==0:
      negatedOdd.append(v)
      negatedEven.append(-v)
    else:
      negatedOdd.append(-v)
      negatedEven.append(v)
  maximum = sum(negatedEven[:d])
  for i in range(0, len(str(n))-d+1):
    if i%2==0:
      current = sum(negatedOdd[i:i+d])
    else:
      current = sum(negatedEven[i:i+d])
    if current > maximum:
      maximum = current
  return maximum

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM