Skip to content

Array Change

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

array_change(inputArray) = 3

Solution

py
def array_change(inputArray):
    count = 0
    for i in range(1, len(inputArray)):
        if inputArray[i] <= inputArray[i - 1]:
            count += inputArray[i - 1] - inputArray[i] + 1
            inputArray[i] = inputArray[i - 1] + 1

    return count


print(array_change([-1000, 0, -2, 0]))
js
function arrayChange(inputArray) {
  let count = 0;
  for (let i = 0; i < inputArray.length; i++) {
    if (inputArray[i] >= inputArray[i + 1]) {
      const diff = inputArray[i] - inputArray[i + 1] + 1;
      inputArray[i + 1] += diff;
      count += diff;
    }
  }
  return count;
}

console.log(arrayChange([-1000, 0, -2, 0]));

my thoughts are neither my employer's nor my wife's