Home > Backend Development > C++ > body text

Which array element has the smallest sum of absolute differences?

PHPz
Release: 2023-08-29 10:09:06
forward
701 people have browsed it

Which array element has the smallest sum of absolute differences?

Here, we will see an interesting question. We have an array 'a' containing N elements. We need to find an element x that minimizes the value of |a[0] - x| |a[1] - x| ... |a[n-1] - x|. Then we need to find the minimized sum.

Suppose the array is: {1, 3, 9, 6, 3}, and now x is 3. So the sum is |1 - 3| |3 - 3| |9 - 3| |6 - 3| |3 - 3| = 11.

To solve this problem, we need to choose the median of the array as x. If the size of the array is even, there will be two median values. They are all the best choices for 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
Copy after login

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);
}
Copy after login

Output

Sum : 11
Copy after login

The above is the detailed content of Which array element has the smallest sum of absolute differences?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template