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

Updated on: 02-Jul-2020

282 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements