产品 python_python系列中最大的产品

为了简单起见,用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值