Files
typescript-katas/5kyu/smallest-possible-sum/solution.ts
2025-02-02 23:52:26 +01:00

58 lines
1.3 KiB
TypeScript

// idea: keep the array sorted
// whenever we execute the subtraction, place the result in the correct position
/**
* Inserts the value in a sorted array to keep it sorted.
* The sort direction is assumed to be ascending.
* @param arr The sorted array
* @param value The value to insert
*/
const sortInsert = (arr: number[], value: number): void => {
let i = 0;
while (i < arr.length && arr[i] < value) {
i++;
}
arr.splice(i, 0, value);
}
/**
* Does a single operation on the given array.
* Keeps the array sorted.
* @returns True if the array is all the same, false otherwise.
*/
const operate = (arr: number[]): boolean => {
// last element is the largest
// find the first element that is not the largest
let i = arr.length - 1;
while (i >= 0 && arr[i] === arr[arr.length - 1]) {
i--;
}
if (i < 0) {
// all elements are the same
return true;
}
// subtract
const value = arr[arr.length - 1] - arr[i];
// remove the last element
arr.pop();
// insert the value in the correct position
sortInsert(arr, value);
return false;
}
export function solution(numbers: number[]): number {
numbers.sort((a, b) => a - b);
let done = false;
while (!done) {
done = operate(numbers);
}
// sum the numbers
return numbers.reduce((acc, num) => acc + num, 0);
}