为了简单起见,用3位数代替13位数。前三位是:731
他们的产品是21。接下来的三位数字是:
^{pr2}$
产品是18。我们需要一个有效的算法,所以我们必须回答的一个问题是:我们能从常数时间的316的乘积中计算出{}的乘积吗?在
答案是肯定的:如果我们看一下数字,从731到{},我们去掉了7,加上了6。但是如果我们看一下乘积,我们得到了除以7,乘以乘以6。我们不用计算7×3×1,然后3×1×6,然后再计算1×6×7,依此类推(每次执行n乘法),我们可以从上一个乘积中计算下一个乘积(只执行1次乘法和1次除法)。在
这是一个在线性时间内运行的高效算法的示意图:def maxproduct(number, digits):
"""Calculate the maximum product of the n-adjacent digits of number."""
zeros = 0
product = 1
result = 0
# Calculate the first, initial product.
for x in number[:digits]:
x = int(x)
if x:
product *= int(x)
else:
# This digit is 0. This will make our product zero
# too (losing information about other digits) and will
# also cause trouble with division later. Instead of
# storing the zero in the product, we increment a counter.
zeros += 1
if not zeros:
# This product is the highest we have seen so far.
result = product
# Calculate the other products with the remaining digits.
for i in range(digits, len(number)):
# Digit to remove.
x = int(number[i - digits])
# Digit to add.
y = int(number[i])
if x:
product //= x
else:
# The digit to remove is 0.
zeros -= 1
if y:
product *= y
else:
zeros += 1
if not zeros and product > result:
result = product
return result