[英]obtain a strictly increasing sequence of the elements of array
So the task is this: You are given an array of integers.所以任务是这样的:给你一个整数数组。 On each move you are allowed to increase exactly one of its element by one.
在每次移动中,您都可以将其元素中的一个精确增加一个。 Find the minimal number of moves required to obtain a strictly increasing sequence from the input.
找出从输入中获得严格递增序列所需的最少移动次数。
EXAMPLE:例子:
input_array = [1, 1, 1], the output should be array_change(input_array) = 3 input_array = [1, 1, 1],输出应该是array_change(input_array) = 3
this is my code and it works fine, it counts the moves correctly but for larger arrays it operates very slow.这是我的代码,它工作正常,它正确计算移动,但对于较大的数组,它的运行速度非常慢。 how can i optimize my code to do the same but faster?
我如何优化我的代码以执行相同但更快的操作? or is there just a better and faster way to do it?
还是只有更好更快的方法来做到这一点? MY CODE:
我的代码:
def array_change(input_array):
l = len(input_array)
k = 0
for i in range(1, l):
while input_array[i - 1] >= input_array[i]:
input_array[i] += 1
k += 1
if input_array[i - 1] == input_array[i]:
input_array[i] += 1
k += 1
return k
ok i just got the right way to do this.好的,我只是找到了正确的方法来做到这一点。
def arrayChange(iA):
c = 0
for i in range(len(iA) - 1):
if iA[i] >= iA[i + 1]:
d = iA[i] - iA[i + 1]
iA[i + 1] += d + 1
c += d + 1
return c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.