- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Absolute Values Sum Minimization in JavaScript
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
- Related Articles
- Absolute sum of array elements - JavaScript
- Taking the absolute sum of Array of Numbers in JavaScript
- Minimization of ER Diagram
- Sum all duplicate values in array in JavaScript
- What is Minimization of DFA?
- Filter unique array values and sum in JavaScript
- JavaScript reduce sum array with undefined values
- JavaScript Sum odd indexed and even indexed elements separately and return their absolute difference
- Sum from array values with similar key in JavaScript
- Sum of nested object values in Array using JavaScript
- How to replace auto-labelled relative values by absolute values in Matplotlib?
- Program to find minimum absolute sum difference in Python
- Calculate the absolute value of float values in Numpy
- Finding the sum of unique array values - JavaScript
- Absolute difference of corresponding digits in JavaScript
