third solution
This commit is contained in:
@@ -11,24 +11,34 @@ const operate = (arr: number[]): boolean => {
|
||||
// find the first element that is not the largest
|
||||
const first = arr[0]; // smallest
|
||||
|
||||
// subtract as many multiples of the smallest number from all the rest
|
||||
let i = 1;
|
||||
|
||||
// if all numbers are the same, return true
|
||||
// if the array is sorted, it is enough to compare the first and last elements
|
||||
if(arr[arr.length - 1] === first) return true;
|
||||
|
||||
while (i < arr.length) {
|
||||
const div = arr[i] / first;
|
||||
let flooredDiv = Math.floor(arr[i] / first);
|
||||
|
||||
if(flooredDiv === div && flooredDiv > 0) {
|
||||
flooredDiv--;
|
||||
// if the first number is 1, set all numbers to 1
|
||||
if(first === 1) {
|
||||
for(let i = 1; i < arr.length; i++) {
|
||||
arr[i] = 1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// subtract as many multiples of the smallest number from all the rest
|
||||
let i = 1;
|
||||
while (i < arr.length) {
|
||||
if(arr[i] <= first) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const mod = arr[i] % first;
|
||||
|
||||
const newValue = arr[i] - first * flooredDiv;
|
||||
if (newValue !== 0) {
|
||||
arr[i] = newValue;
|
||||
if (mod === 0) {
|
||||
// figure out how many times the first number can be subtracted from the current number
|
||||
const div = arr[i] / first - 1;
|
||||
arr[i] = arr[i] - first * div;
|
||||
} else {
|
||||
arr[i] = mod;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user