-1

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?

user21
  • 249
  • 3
  • 13

3 Answers3

2

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.

fileyfood500
  • 1,199
  • 1
  • 13
  • 29
1

@fileyfood500 gave me a very usefull hint and here is my solution that works:

deltX=0
for i in range(len(a)-1):
    if (a[i]<a[i+1]) == False:
        deltX1 = abs(a[i+1]-a[i])+1
        a[i+1] = a[i+1] + deltX1
        deltX += deltX1
print(deltX)

Now I do not need while loop at all because I increase the item, that should be increased by necessary number in one step.

user21
  • 249
  • 3
  • 13
1
def arrayChange(inputArray):
    count = 0
    for i in range(1,len(inputArray)):
        while inputArray[i] <= inputArray[i-1]:
            c = inputArray[i]
            inputArray[i]= inputArray[i-1]+1
            count += inputArray[i] - c 
    return count

This way you increment it directly and the time will be less.
Then just subtract the new value from the earlier one to get the number of times it increments.

סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68