Wednesday, 27 Oct 2021

# Array element with minimum sum of absolute differences | Set 2

Given an array arr[] consisting of N positive integers, the task is to find an array element X such that sum of its absolute differences with every array element is minimum.Examples:Input: arr[] = {1, 2, 3, 4, 5}Output: 3Explanation:For element arr(= 1): |(1 – 1)| + |(2 – 1)| + |(3 – 1)| + |(4 – 1)| + |(5 – 1)| = 0 + 1 + 2 + 3 + 4 = 10.For element arr(= 2): |(1 – 2)| + |(2 – 2)| + |(3 – 2)| + |(4 – 2)| + |(5 – 2)| = 1 + 0 + 1 + 2 + 3 = 7.For element arr(= 3): |(1 – 3)| + |(2 – 3)| + |(3 – 3)| + |(4 – 3)| + |(5 – 3)| = 2 + 1 + 0 + 1 + 2 = 6.For element arr(= 4): |(1 – 4)| + |(2 – 4)| + |(3 – 4)| + |(4 – 4)| + |(5 – 4)| = 3 + 2 + 1 + 0 + 1 = 7.For element arr(= 5): |(1 – 5)| + |(2 – 5)| + |(3 – 5)| + |(4 – 5)| + |(5 – 5)| = 4 + 3 + 2 + 1 + 0 = 10.Therefore, the element having minimum sum of absolute differences with all array elements is 3.Input: arr[] = {15, 12, 13, 10}Output: 12Naive Approach: The simplest approach to solve the given problem is to find the sum of absolute differences of array elements with every element of the array one by one, and print that element that has the smaller sum of differences.Time Complexity: O(N2)Auxiliary Space: O(1)Median-based Approach: Refer to the previous post of this article to solve this problem using median-finding technique.Time Complexity: O(NlogN)Auxiliary Space: O(1)Efficient Approach: The above approach can also be optimized by minimizing the value of (sum of all the array elements – X*N) for each array element X and find the resultant element X. Follow the steps below to solve the problem:Initialize a variable, say res as arr that stores the resultant array element whose sum of absolute differences of array elements with res is minimum.Find the sum of the array elements and store it in the variable, say sum.Initialize a variable, say minDiff as the value of the sum.Traverse the given array arr[] and if the absolute value of (sum – (arr[i] * N)) is less than minDiff then update minDiff to this value and res as the current array element i.e., arr[i].After completing the above steps, print the value of res as the resultant array element.Below is the implementation of the above approach:C++  #include using namespace std;  int minimumDiff(int arr[], int N){            int res = arr, sum = 0;          for (int i = 0; i < N; i++)        sum += arr[i];              int min_diff = sum;              for (int i = 0; i < N; i++) {                                  if (abs(sum - (arr[i] * N))            < min_diff) {                          min_diff = abs(sum - (arr[i] * N));            res = arr[i];        }    }          cout