Code Signal – 改变数组(arrayChange)

Code Signal – 改变数组(arrayChange)

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:

For inputArray = [1, 1, 1], the output should be arrayChange(inputArray) = 3.

Input/Output:

[execution time limit] 4 seconds (js)

[input] array.integer inputArray

Guaranteed constraints:

3 ≤ inputArray.length ≤ 105,

-105 ≤ inputArray[i] ≤ 105.

[output] integer

The minimal number of moves needed to obtain a strictly increasing sequence from inputArray.

It’s guaranteed that for the given test cases the answer always fits signed 32-bit integer type.

解题思路
这道题主要就是问,当前数组是否是 严格增长 数组,即数组中的所有数字,下一个下标的数字必须大于上一个下标的数字。

如,[1, 1, 1] 需要改为 严格增长 数组,就需要将其改为 [1, 2, 3],而所需要花费的最小数字就是 2 − 1 + 3 − 1 = 2 2 – 1 + 3 – 1 = 22−1+3−1=2。

所以在这里就可以做一次迭代,检查 当前下标的值 是否比 上一个下标的值 大,如果不是,判断最少需要多少数字使得 当前下标的值 比 上一个下标的值 大,随后更新 当前下标的值,并将总数累积起来,最后返回。

记录一下这道题主要还是为了记录一下 array.reduce() 的使用,毕竟 array.reduce() 相对于其他函数来说,使用的频率确实低了不少。
 

class Solution:
    def arrayChange(inputArray):
        print(inputArray)
        minChange = 0
 
        for i in range(1, len(inputArray)):
            localDiff = 0
            if inputArray[i] <= inputArray[i – 1]:
                localDiff = inputArray[i – 1] -inputArray[i] + 1
                inputArray[i] += localDiff
                minChange += localDiff
 
        print(inputArray)
        return minChange
print(arrayChange([1,1,1]))
print(arrayChange([1]))
 
def solution(inputArray):
    number_moves = 0
   
    for i in range(1, len(inputArray)):
        # print(“—————-“)
        # print(i)
        # print(inputArray[i])
        if inputArray[i] <= inputArray[i – 1]:
            diff = inputArray[i-1] – inputArray[i] + 1
            # print(“~~~~”)
            # print(diff)
            inputArray[i] += diff
            number_moves += diff
   
    returnnumber_moves
           
No Comments

Post A Comment