我參加codefights並讓任務找到從輸入中獲得嚴格遞增序列所需的最少移動次數。作爲一個輸入,有整數數組,並且按照規則,我可以每移動一個數組,增加一個數組。如何提高算法性能的速度來計算最小移動次數?
inputArray: [1, 1, 1]
Expected Output:3
inputArray: [-1000, 0, -2, 0]
Expected Output:5
inputArray: [2, 1, 10, 1]
Expected Output:12
inputArray: [2, 3, 3, 5, 5, 5, 4, 12, 12, 10, 15]
Expected Output:13
也有輸入和輸出條件:
[time limit] 4000ms (py3)
[input] array.integer inputArray
3 ≤ inputArray.length ≤ 105,
-105 ≤ inputArray[i] ≤ 105
[output] integer
我與followitn解決方案上來:
def arrayChange(inputArray):
k=0
for i in range(len(inputArray)-1):
if (inputArray[i]<inputArray[i+1]) == False:
while inputArray[i+1]<=inputArray[i]:
inputArray[i+1] = inputArray[i+1] + 1
k +=1
return k
然而,apperantly對於一些測試,我不能看到我的算法性能超出時間限制:
6/8 測試7超出執行時間限制:程序超出執行時間限制。確保它在幾秒鐘內完成執行任何可能的輸入。 樣品測試:4/4 隱藏測試:2/4
如何提高我的提高性能速度的算法?