Given an array of integers, what's the most efficient way to perform j
operations on the array where the value of j
could be =>
or <=
array.length
?
I tried something like this...
function performJ(arr, j) {
arr.sort((a, b) => b - a);
let i = 0;
while (j !== 0) {
if (i < arr.length) {
arr[i] = Math.ceil(arr[i] / 2)
} else {
// when i reaches arr.length, reset it to continue operations j
i = 0;
arr[i] = Math.ceil(arr[i] / 2)
}
// increment i, step through arr
++i;
// decrement j as we perform operations on arr
--j;
}
return arr.reduce((a, b) => a + b);
}
That works for a lot of cases, but for some reason it seems like large inputs of arr
and j
cause arithmetic operations in the while
loop to get way off.
Thanks!
EDIT: Edited question for clarity. I previously had a solution that worked, but it took way too long. This solution's arithmetic is off, but works much faster.