Array Change
Description
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 \leq inputArray.length \leq 10^5
,
-10^5 \leq inputArray[i] \leq 10^5
.
- [output] boolean
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.
[JavaScript (ES6)] Syntax Tips
1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
console.log("This prints to the console when you Run Tests");
return "Hello, " + name;
}
Solution
1
2
3
4
5
6
7
8
9
10
11
12
function arrayChange(inputArray) {
var max = inputArray[0];
var moves = 0;
for(var i = 1; i < inputArray.length; i++) {
if (inputArray[i] <= max) {
moves += max - inputArray[i] + 1;
inputArray[i] = max + 1;
}
max = inputArray[i]
}
return moves
}