Make Array Consecutive 2
Description
Ratiorg got statues
of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by 1
. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of additional statues needed.
Example
For statues = [6, 2, 3, 8]
, the output should be
makeArrayConsecutive2(statues) = 3
.
Ratiorg needs statues of sizes 4
, 5
and 7
.
Input/Output
-
[execution time limit] 4 seconds (js)
-
[input] array.integer statues
An array of distinct non-negative integers.
Guaranteed constraints:
1 ≤ statues.length ≤ 10
,
0 ≤ statues[i] ≤ 20
. -
[output] integer
- The minimal number of statues that need to be added to existing
statues
such that it contains every integer size from an interval[L, R]
(for someL, R
) and no other sizes.
- The minimal number of statues that need to be added to existing
[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
function makeArrayConsecutive2(statues) {
var s = 0;
statues.sort((a, b) => a - b);
for (var i = 1; i < statues.length; i++) {
s += statues[i] - statues[i - 1] - 1;
}
return s;
}