Open In App

Array element with minimum sum of absolute differences

Last Updated : 23 Nov, 2023
Comments
Improve
Suggest changes
2 Likes
Like
Report

Given an array arr[] of N integers, the task is to find an element x from the array such that |arr[0] - x| + |arr[1] - x| + |arr[2] - x| + ... + |arr[n - 1] - x| is minimized, then print the minimized sum.

Examples: 

Input: arr[] = {1, 3, 9, 3, 6} 
Output: 11 
The optimal solution is to choose x = 3, which produces the sum 
|1 - 3| + |3 - 3| + |9 - 3| + |3 - 3| + |6 - 3| = 2 + 0 + 6 + 0 + 3 = 11

Input: arr[] = {1, 2, 3, 4} 
Output:

A simple solution is to iterate through every element and check if it gives optimal solution or not. Time Complexity of this solution is O(n*n).

Algorithm:

Below is the implementation of the approach:

C++
Java Python3 C# JavaScript

Output
11

An Efficient Approach: is to always pick x as the median of the array. If n is even and there are two medians then both the medians are optimal choices. The time complexity for the approach is O(n * log(n)) because the array will have to be sorted in order to find the median. Calculate and print the minimized sum when x is found (median of the array).

Below is the implementation of the above approach: 

C++
Java Python3 C# JavaScript

Output
11

Time Complexity: O(n log n), where n is the size of the given array.
Auxiliary Space: O(1), no extra space is required.

We can further optimize it to work in O(n) using linear time algorithm to find k-th largest element.


Next Article

Similar Reads