简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM