-
-
Save Nicknyr/725163efc5c3da0d2ca59609bac4cdc1 to your computer and use it in GitHub Desktop.
| /* | |
| 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. | |
| */ | |
| function makeArrayConsecutive2(statues) { | |
| let statuesNeeded = 0; | |
| // Sort array smallest to largest | |
| statues.sort((a, b) => { | |
| return a - b; | |
| }) | |
| // Iterate through array and find gaps in values | |
| for(let i = 0; i < statues.length; i++) { | |
| // If there is a gap between neighboring numbers subtract higher number from lower number i.e. [3, 6] is 6 - 3. There is a gap of 3, so 2 numbers are missing i.e. 4, 5 | |
| if(statues[i + 1] - statues[i] > 1) { | |
| statuesNeeded += statues[i + 1] - statues[i] - 1; | |
| } | |
| } | |
| return statuesNeeded; | |
| } |
Javascript version
I used javascript to solve the problem, I used reduce to calculate the minimum number of additional statues in a single line.
The reduction function checks the difference between each pair of adjacent statues and accumulates these differences into a total.
function solution(statues) {
statues.sort((a, b) => a - b);
return statues.reduce((total, current, index, array) => index < array.length - 1 ? total + array[index + 1] - current - 1 : total, 0);
}
Here is another logic, a l'll different but works all good
Javascript
function solution(statues) {
var statues1 = statues.sort((a,b) => {
return a-b;
});
console.log(statues1.valueOf());
const L = statues[0];
const R = statues[statues.length-1];
var count = 0;
for (var i=L;i<=R;i++){
if(statues.includes(i)==false){
count = count + 1;
}
}
return count;
}
java version working :
boolean solution(int[] sequence) {
// [1, 2, 1, 2]
// i-2, i-1, i, i+1
// Stores the count of numbers that are needed to be removed
int count = 0;
}