
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Array element with minimum sum of absolute differences?
Here we will see one interesting problem. We are taking one array ‘a’ with N elements. We have to find an element x such that |a[0] - x| + |a[1] - x|+ … + |a[n-1] - x| is minimized. Then we have to find the minimized sum.
Let the array is: {1, 3, 9, 6, 3} now the x is 3. So the sum is |1 - 3| + |3 - 3| + |9 - 3| + |6 - 3| + |3 - 3| = 11.
To solve this problem, we have to choose the median of the array as x. If the array size is even, then two median values will be there. Both of them will be an optimal choice of x.
Algorithm
minSum(arr, n)
begin sort array arr sum := 0 med := median of arr for each element e in arr, do sum := sum + |e - med| done return sum end
Example
#include <iostream> #include <algorithm> #include <cmath> using namespace std; int minSum(int arr[], int n){ sort(arr, arr + n); int sum = 0; int med = arr[n/2]; for(int i = 0; i<n; i++){ sum += abs(arr[i] - med); } return sum; } int main() { int arr[5] = {1, 3, 9, 6, 3}; int n = 5; cout << "Sum : " << minSum(arr, n); }
Output
Sum : 11
- Related Questions & Answers
- Array element with minimum sum of absolute differences in C++?
- Absolute sum of array elements - JavaScript
- Program to find sum of absolute differences in a sorted array in Python
- Program to find minimum absolute sum difference in Python
- Taking the absolute sum of Array of Numbers in JavaScript
- Find minimum element of ArrayList with Java Collections
- Program to find the sum of the absolute differences of every pair in a sorted list in Python
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array?
- Finding sum of every nth element of array in JavaScript
- Absolute Values Sum Minimization in JavaScript
- Maximum sum of absolute difference of any permutation in C++
- Sorting and find sum of differences for an array using JavaScript
- Find an element in array such that sum of left array is equal to sum of right array using c++
- Sum of subset differences in C++
- Minimum sum of two numbers formed from digits of an array in C++
Advertisements