Search code examples
algorithmperformancepython-3.xloopscycle

How to increase speed of algorithm performance for calculation minimal number of moves?


I participate codefights and have the task find the minimal number of moves that are required to obtain a strictly increasing sequence from the input. As an input there are arrays of integers and accourding to the rule I can increase exactly one element an array by one per one move.

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

There are also conditions for input and output:

[time limit] 4000ms (py3)
[input] array.integer inputArray
3 ≤ inputArray.length ≤ 105,
-105 ≤ inputArray[i] ≤ 105
[output] integer

I came up with the followitn solution:

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

However, apperantly for some tests that I cannot observe my algorithm performance is out of the time limits:

6/8 Execution time limit exceeded on test 7: Program exceeded the execution time limit. Make sure that it completes execution in a few seconds for any possible input. Sample tests: 4/4 Hidden tests: 2/4

How to improve my algorithm for increasing performance speed?


Solution

  • Right now you increase by 1 at a time. Currently you have this code snippet:

    inputArray[i+1] = inputArray[i+1] + 1

    Instead of incrementing by 1 each time, why not add all of the numbers at once? For example, if you have the list [1, 3, 0] it makes sense to add 4 to the last element. Doing this would go much more quickly than adding 1 4 times.