Skip to content
Related Articles

Related Articles

Improve Article
Array element with minimum sum of absolute differences | Set 2
  • Difficulty Level : Easy
  • Last Updated : 27 Apr, 2021

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: 3
Explanation:

  1. For element arr[0](= 1): |(1 – 1)| + |(2 – 1)| + |(3 – 1)| + |(4 – 1)| + |(5 – 1)| = 0 + 1 + 2 + 3 + 4 = 10.
  2. For element arr[1](= 2): |(1 – 2)| + |(2 – 2)| + |(3 – 2)| + |(4 – 2)| + |(5 – 2)| = 1 + 0 + 1 + 2 + 3 = 7.
  3. For element arr[2](= 3): |(1 – 3)| + |(2 – 3)| + |(3 – 3)| + |(4 – 3)| + |(5 – 3)| = 2 + 1 + 0 + 1 + 2 = 6.
  4. For element arr[3](= 4): |(1 – 4)| + |(2 – 4)| + |(3 – 4)| + |(4 – 4)| + |(5 – 4)| = 3 + 2 + 1 + 0 + 1 = 7.
  5. For element arr[4](= 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: 12



Naive 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[0] 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++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the element with
// minimum sum of differences between
// any elements in the array
int minimumDiff(int arr[], int N)
{
    // Stores the required X and
    // sum of absolute differences
    int res = arr[0], sum = 0;
 
    // Calculate sum of array elements
    for (int i = 0; i < N; i++)
        sum += arr[i];
 
    // The sum of absolute differences
    // can't be greater than sum
    int min_diff = sum;
 
    // Update res that gives
    // the minimum sum
    for (int i = 0; i < N; i++) {
 
        // If the current difference
        // is less than the previous
        // difference
        if (abs(sum - (arr[i] * N))
            < min_diff) {
 
            // Update min_diff and res
            min_diff = abs(sum - (arr[i] * N));
            res = arr[i];
        }
    }
 
    // Print the resultant value
    cout << res;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
    minimumDiff(arr, N);
 
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
 
class GFG{
 
// Function to find the element with
// minimum sum of differences between
// any elements in the array
static void minimumDiff(int[] arr, int N)
{
     
    // Stores the required X and
    // sum of absolute differences
    int res = arr[0], sum = 0;
 
    // Calculate sum of array elements
    for(int i = 0; i < N; i++)
        sum += arr[i];
 
    // The sum of absolute differences
    // can't be greater than sum
    int min_diff = sum;
 
    // Update res that gives
    // the minimum sum
    for(int i = 0; i < N; i++)
    {
         
        // If the current difference
        // is less than the previous
        // difference
        if (Math.abs(sum - (arr[i] * N)) < min_diff)
        {
             
            // Update min_diff and res
            min_diff = Math.abs(sum - (arr[i] * N));
            res = arr[i];
        }
    }
 
    // Print the resultant value
    System.out.println(res);
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = arr.length;
     
    minimumDiff(arr, N);
}
}
 
// This code is contributed by subham348

C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to find the element with
// minimum sum of differences between
// any elements in the array
static void minimumDiff(int[] arr, int N)
{
     
    // Stores the required X and
    // sum of absolute differences
    int res = arr[0], sum = 0;
 
    // Calculate sum of array elements
    for(int i = 0; i < N; i++)
        sum += arr[i];
 
    // The sum of absolute differences
    // can't be greater than sum
    int min_diff = sum;
 
    // Update res that gives
    // the minimum sum
    for(int i = 0; i < N; i++)
    {
         
        // If the current difference
        // is less than the previous
        // difference
        if (Math.Abs(sum - (arr[i] * N)) < min_diff)
        {
             
            // Update min_diff and res
            min_diff = Math.Abs(sum - (arr[i] * N));
            res = arr[i];
        }
    }
 
    // Print the resultant value
    Console.Write(res);
}
 
// Driver Code
public static void Main()
{
    int []arr = { 1, 2, 3, 4, 5 };
    int N = arr.Length;
     
    minimumDiff(arr, N);
}
}
 
// This code is contributed by subham348

Python3




# python 3 program for the above approach
 
# Function to find the element with
# minimum sum of differences between
# any elements in the array
def minimumDiff(arr, N):
   
    # Stores the required X and
    # sum of absolute differences
    res = arr[0]
    sum1 = 0
 
    # Calculate sum of array elements
    for i in range(N):
        sum1 += arr[i]
 
    # The sum of absolute differences
    # can't be greater than sum
    min_diff = sum1
 
    # Update res that gives
    # the minimum sum
    for i in range(N):
       
        # If the current difference
        # is less than the previous
        # difference
        if (abs(sum1 - (arr[i] * N)) < min_diff):
           
            # Update min_diff and res
            min_diff = abs(sum1 - (arr[i] * N))
            res = arr[i]
 
    # Print the resultant value
    print(res)
 
# Driver Code
if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5]
    N = len(arr)
    minimumDiff(arr, N)
     
    # This code is contributed by SURENDRA_GANGWAR.

Javascript




<script>
// Javascript program for the above approach
 
// Function to find the element with
// minimum sum of differences between
// any elements in the array
function minimumDiff(arr, N)
{
    // Stores the required X and
    // sum of absolute differences
    let res = arr[0], sum = 0;
 
    // Calculate sum of array elements
    for (let i = 0; i < N; i++)
        sum += arr[i];
 
    // The sum of absolute differences
    // can't be greater than sum
    let min_diff = sum;
 
    // Update res that gives
    // the minimum sum
    for (let i = 0; i < N; i++) {
 
        // If the current difference
        // is less than the previous
        // difference
        if (Math.abs(sum - (arr[i] * N))
            < min_diff) {
 
            // Update min_diff and res
            min_diff = Math.abs(sum - (arr[i] * N));
            res = arr[i];
        }
    }
 
    // Print the resultant value
    document.write(res);
}
 
// Driver Code
    let arr = [ 1, 2, 3, 4, 5 ];
    let N = arr.length;
    minimumDiff(arr, N);
 
</script>
Output: 
3

 

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live 




My Personal Notes arrow_drop_up
Recommended Articles
Page :