Suppose, we are given a sorted array of integers, let us call it arr. We are required to find such an integer x that the value of −
abs(a[0] - x) + abs(a[1] - x) + ... + abs(a[a.length - 1] - x)
is the smallest possible (here abs denote the absolute value). If there are several possible answers, output the smallest one.
For example −
For,
arr = [2, 4, 7],
the output should be −
absoluteValuesSumMinimization(arr) = 4
because abs(2 - 4) + abs(4 - 4) + abs(7 - 4) = 5 which is the smallest we can achieve with any number.
We know that,
arr.length/2
returns half the length.
For even-length arrays, this will be to the right of the middle. For odd-length arrays, it'll be the middle.
Math.ceil(arr.length/2) rounds up if necessary, so the middle of an array of 5 would be 2.5 -> 3. This makes the odd-length arrays off by one.
Math.ceil(arr.length/2)-1 goes down one index. This corrects off-by-one errors for all the arrays.
Example
Following is the code −
const arr = [2, 4, 7];
const absoluteValuesSumMinimization = (arr = []) => {
const res = [];
arr.forEach(num => {
const sum = arr.reduce((accum, next) => {
return accum + Math.abs(next - num);
}, 0);
res.push(sum);
});
const lowest = Math.min(...res);
return arr[res.indexOf(lowest)];
};
console.log(absoluteValuesSumMinimization(arr));Output
Following is the output on console −
4