Array element with minimum sum of absolute differences
Last Updated :
23 Nov, 2023
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: 4
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++
// C++ code for the approach
#include<bits/stdc++.h>
using namespace std;
// Function to find the minimum sum of absolute differences
int findMinSum(int arr[], int n) {
// Initialize the minimum sum and minimum element
int minSum = INT_MAX, minElement = -1;
// Traverse through all elements of the array
for (int i = 0; i < n; i++) {
int sum = 0;
// Calculate the sum of absolute differences
// of each element with the current element
for (int j = 0; j < n; j++) {
sum += abs(arr[i] - arr[j]);
}
// Update the minimum sum and minimum element
if (sum < minSum) {
minSum = sum;
minElement = arr[i];
}
}
// Return the minimum sum
return minSum;
}
// Driver code
int main() {
int arr[] = { 1, 3, 9, 3, 6 };
int n = sizeof(arr)/sizeof(arr[0]);
// Find the minimum sum of absolute differences
int minSum = findMinSum(arr, n);
// Print the minimum sum
cout << minSum << endl;
return 0;
}
Java
// Java code for the approach
import java.util.*;
public class GFG {
// Function to find the minimum sum of absolute differences
public static int findMinSum(int[] arr, int n) {
// Initialize the minimum sum and minimum element
int minSum = Integer.MAX_VALUE, minElement = -1;
// Traverse through all elements of the array
for (int i = 0; i < n; i++) {
int sum = 0;
// Calculate the sum of absolute differences
// of each element with the current element
for (int j = 0; j < n; j++) {
sum += Math.abs(arr[i] - arr[j]);
}
// Update the minimum sum and minimum element
if (sum < minSum) {
minSum = sum;
minElement = arr[i];
}
}
// Return the minimum sum
return minSum;
}
// Driver code
public static void main(String[] args) {
int[] arr = {1, 3, 9, 3, 6};
int n = arr.length;
// Find the minimum sum of absolute differences
int minSum = findMinSum(arr, n);
// Print the minimum sum
System.out.println(minSum);
}
}
Python3
# Python3 code for the approach
import sys
# Function to find the minimum sum of absolute differences
def findMinSum(arr, n):
# Initialize the minimum sum and minimum element
minSum = sys.maxsize
minElement = -1
# Traverse through all elements of the array
for i in range(n):
sum = 0
# Calculate the sum of absolute differences
# of each element with the current element
for j in range(n):
sum += abs(arr[i] - arr[j])
# Update the minimum sum and minimum element
if (sum < minSum):
minSum = sum
minElement = arr[i]
# Return the minimum sum
return minSum
# Driver code
if __name__ == '__main__':
arr = [1, 3, 9, 3, 6]
n = len(arr)
# Find the minimum sum of absolute differences
minSum = findMinSum(arr, n)
# Print the minimum sum
print(minSum)
C#
using System;
class Program
{
// Function to find the minimum sum of absolute differences
static int FindMinSum(int[] arr, int n)
{
// Initialize the minimum sum
int minSum = int.MaxValue;
// Traverse through all elements of the array
for (int i = 0; i < n; i++)
{
int sum = 0;
// Calculate the sum of absolute differences
// of each element with the current element
for (int j = 0; j < n; j++)
{
sum += Math.Abs(arr[i] - arr[j]);
}
// Update the minimum sum
if (sum < minSum)
{
minSum = sum;
}
}
// Return the minimum sum
return minSum;
}
// Driver code
static void Main()
{
int[] arr = { 1, 3, 9, 3, 6 };
int n = arr.Length;
// Find the minimum sum of absolute differences
int minSum = FindMinSum(arr, n);
// Print the minimum sum
Console.WriteLine(minSum);
}
}
JavaScript
// Function to find the minimum sum of absolute differences
function findMinSum(arr) {
// Initialize the minimum sum and minimum element
let minSum = Infinity;
let minElement = -1;
// Traverse through all elements of the array
for (let i = 0; i < arr.length; i++) {
let sum = 0;
// Calculate the sum of absolute differences
// of each element with the current element
for (let j = 0; j < arr.length; j++) {
sum += Math.abs(arr[i] - arr[j]);
}
// Update the minimum sum and minimum element
if (sum < minSum) {
minSum = sum;
minElement = arr[i];
}
}
// Return the minimum sum
return minSum;
}
// Driver code
const arr = [1, 3, 9, 3, 6];
const minSum = findMinSum(arr);
// Print the minimum sum
console.log(minSum);
// This code is contributed by shivamgupta0987654321
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++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the minimized sum
int minSum(int arr[], int n)
{
// Sort the array
sort(arr, arr + n);
// Median of the array
int x = arr[n / 2];
int sum = 0;
// Calculate the minimized sum
for (int i = 0; i < n; i++)
sum += abs(arr[i] - x);
// Return the required sum
return sum;
}
// Driver code
int main()
{
int arr[] = { 1, 3, 9, 3, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << minSum(arr, n);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
// Function to return the minimized sum
static int minSum(int arr[], int n)
{
// Sort the array
Arrays.sort(arr);
// Median of the array
int x = arr[(int)n / 2];
int sum = 0;
// Calculate the minimized sum
for (int i = 0; i < n; i++)
sum += Math.abs(arr[i] - x);
// Return the required sum
return sum;
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 3, 9, 3, 6 };
int n = arr.length;
System.out.println(minSum(arr, n));
}
}
// This code is contribute by
// Surendra_Gangwar
Python3
# Python3 implementation of the approach
# Function to return the minimized sum
def minSum(arr, n) :
# Sort the array
arr.sort();
# Median of the array
x = arr[n // 2];
sum = 0;
# Calculate the minimized sum
for i in range(n) :
sum += abs(arr[i] - x);
# Return the required sum
return sum;
# Driver code
if __name__ == "__main__" :
arr = [ 1, 3, 9, 3, 6 ];
n = len(arr)
print(minSum(arr, n));
# This code is contributed by Ryuga
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the minimized sum
static int minSum(int []arr, int n)
{
// Sort the array
Array.Sort(arr);
// Median of the array
int x = arr[(int)(n / 2)];
int sum = 0;
// Calculate the minimized sum
for (int i = 0; i < n; i++)
sum += Math.Abs(arr[i] - x);
// Return the required sum
return sum;
}
// Driver code
static void Main()
{
int []arr = { 1, 3, 9, 3, 6 };
int n = arr.Length;
Console.WriteLine(minSum(arr, n));
}
}
// This code is contributed by mits
JavaScript
<script>
//Javascript implementation of the approach
// Function to return the minimized sum
function minSum(arr, n)
{
// Sort the array
arr.sort();
// Median of the array
let x = arr[(Math.floor(n / 2))];
let sum = 0;
// Calculate the minimized sum
for (let i = 0; i < n; i++)
sum += Math.abs(arr[i] - x);
// Return the required sum
return sum;
}
// Driver code
let arr = [ 1, 3, 9, 3, 6 ];
let n = arr.length;
document.write(minSum(arr, n));
// This code is contributed by Mayank Tyagi
</script>
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.
Similar Reads
Sum of absolute differences of indices of occurrences of each array element Given an array arr[] consisting of N integers, the task for each array element arr[i] is to print the sum of |i - j| for all possible indices j such that arr[i] = arr[j]. Examples: Input: arr[] = {1, 3, 1, 1, 2}Output: 5 0 3 4 0Explanation: For arr[0], sum = |0 - 0| + |0 - 2| + |0 - 3| = 5. For arr[
10 min read
Count pairs from an array with absolute difference not less than the minimum element in the pair Given an array arr[] consisting of N positive integers, the task is to find the number of pairs (arr[i], arr[j]) such that absolute difference between the two elements is at least equal to the minimum element in the pair. Examples: Input: arr[] = {1, 2, 2, 3}Output: 3Explanation:Following are the pa
14 min read
Print distinct absolute differences of all possible pairs from a given array Given an array, arr[] of size N, the task is to find the distinct absolute differences of all possible pairs of the given array.Examples:Input: arr[] = { 1, 3, 6 } Output: 2 3 5 Explanation: abs(arr[0] - arr[1]) = 2 abs(arr[1] - arr[2]) = 3 abs(arr[0] - arr[2]) = 5 Input: arr[] = { 5, 6, 7, 8, 14, 1
9 min read
Sort an array according to absolute difference with given value using Functors Given an array of n distinct elements and a number x, arrange array elements according to the absolute difference with x, i. e., the element having a minimum difference comes first and so on. Note: If two or more elements are at equal distance arrange them in same sequence as in the given array. Exa
6 min read
Missing occurrences of a number in an array such that maximum absolute difference of adjacent elements is minimum Given an array arr[] of some positive integers and missing occurrence of a specific integer represented by -1, the task is to find that missing number such that maximum absolute difference between adjacent elements is minimum.Examples: Input: arr[] = {-1, 10, -1, 12, -1} Output: 11 Explanation: Diff
6 min read
Maximum value of X such that difference between any array element and X does not exceed K Given an array arr[] consisting of N positive integers and a positive integer K, the task is to find the maximum possible integer X, such that the absolute difference between any array element and X is at most K. If no such value of X exists, then print "-1". Examples: Input: arr[] = {6, 4, 8, 5}, K
10 min read
Partitioning into two contiguous element subarrays with equal sums Given an array of n positive integers. Find a minimum positive element to be added to one of the indexes in the array such that it can be partitioned into two contiguous sub-arrays of equal sums. Output the minimum element to be added and the position where it is to be added. If multiple positions a
10 min read
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[0](= 1): |(1 - 1)| + |(2 - 1)| + |(3 - 1)| + |(4
7 min read
Sum of minimum absolute differences in an array Given an array of n distinct integers. The task is to find the sum of minimum absolute difference of each array element. For an element arr[i] present at index i in the array, its minimum absolute difference is calculated as: Min absolute difference (arr[i]) = min(abs(arr[i] - arr[j])), where 0 <
7 min read
k-th smallest absolute difference of two elements in an array We are given an array of size n containing positive integers. The absolute difference between values at indices i and j is |a[i] - a[j]|. There are n*(n-1)/2 such pairs and we are asked to print the kth (1 <= k <= n*(n-1)/2) as the smallest absolute difference among all these pairs. Examples:
9 min read