From ca92878a0a8b256cb6d9f3b03d33095094447d73 Mon Sep 17 00:00:00 2001 From: Loosetooth Date: Mon, 3 Feb 2025 00:03:07 +0100 Subject: [PATCH] third solution --- 5kyu/smallest-possible-sum/solution.ts | 34 +++++++++++++++++--------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/5kyu/smallest-possible-sum/solution.ts b/5kyu/smallest-possible-sum/solution.ts index ecbd374..7f063b9 100644 --- a/5kyu/smallest-possible-sum/solution.ts +++ b/5kyu/smallest-possible-sum/solution.ts @@ -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++; }