Array element with minimum sum of absolute differences in C++?


This program is to find minimum absolute difference of the array given we have an array which have distinct element.To learn this concept better let’s rebrush the things that required,

Array is a container of elements of same data type. The length of an array needs to be predefined.

absolute difference is the absolute value of the difference between two numbers i.e. the difference will always be positive, negative values will be converted to positive.

The sum of minimum absolute difference of each element has to be found the minimum absolute solute difference formula is

Minimum Absolute Difference (a) = min(abs(a – arr[j])) ;

where 1 <= j <= n and j != i, abs is the absolute value.

Input: arr = {1, 3, 9, 3, 6}
Output: 8

Explanation

The optimal solution is to choose x = 3, which produces the sum

|1 – 3| + |3 – 3| + |9 – 3| + |3 – 3| = 2 + 0 + 6 + 0 = 8

Algorithm

  • The given input array is sorted.

  • minimum absolute difference for the first element of the array, is calculated using the second array element.

  • minimum absolute difference for the last array element, is also calculated using the second last array element.

  • , minimum absolute difference for the other array elements which hare present at index i are calculated by :

  • minAbsDiff = min( abs(arr[i] – arr[i-1]), abs(ar[i] – arr[i+1]) ).

Example

 Live Demo

#include<iostream>
#include <algorithm>
using namespace std;
int abs_sum(int a[], int len);
int main() {
   int a[]={1, 3, 9, 3, 6};
   int n, i;
   n=5;
   sort(a, a+n);
   int sum = 0;
   sum += abs(a[0]- a[1]);
   sum += abs(a[n-1]-a[n-2]);
   for (int i = 1; i < n-1; i++) {
      sum += min(abs(a[i]-a[i-1]), abs(a[i]-a[i+1]));
   }
   cout<<"The element with minimum sum of absolute differences is : "<<sum;
   return 0;
}

Output

The element with minimum sum of absolute differences is : 8

Updated on: 04-Oct-2019

257 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements