Minimum sum of differences with an element in an array - GeeksforGeeks

18 May, 2021
Given an array, we need to find the sum of elements of an array after changing the element as arr[i] will become abs(arr[i]-x) where x is an array element.
Examples: 
Input  : {2, 5, 1, 7, 4}
Output : 9
We get minimum sum when we choose
x = 4. The minimum sum is 
abs(2-4) + abs(5-4) + abs(1-4) + (7-4)
abs(4-4) = 9

Input  : {5, 11, 14, 10, 17, 15}
Output : 20
We can either choose x = 14 or x = 11
The idea is based on fact that middle element would cause minimum sum of differences. When there are even number of elements, we can take any of the middle two elements. We can verify this fact by taking few examples. 
Below is the implementation of above idea:  
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find minimum sum of absolute// differences with an array element.#include<bits/stdc++.h>using namespace std;    // function to find min sum after operation    int absSumDidd(int a[],int n)    {        // Sort the array        sort(a,a+n);                 // Pick middle value        int midValue = a[(int)(n / 2)];         // Sum of absolute differences.        int sum = 0;        for (int i = 0; i < n; i++) {            sum = sum + abs(a[i] - midValue);        }                 return sum;        }     // Driver Code    int main()    {        int arr[] = { 5, 11, 14, 10, 17, 15 };        int n=sizeof(arr)/sizeof(arr[0]);        cout<< absSumDidd(arr,n);        }    // Contributed by mits
// Java program to find minimum sum of absolute// differences with an array element.import java.lang.*;import java.util.*; public class GFG {     // function to find min sum after operation    static int absSumDidd(int a[])    {        // Sort the array        Arrays.sort(a);                 // Pick middle value        int midValue = a[a.length / 2];         // Sum of absolute differences.        int sum = 0;        for (int i = 0; i < a.length; i++) {            sum = sum + Math.abs(a[i] - midValue);        }                return sum;          }     // Driver Code    public static void main(String[] args)    {        int arr[] = { 5, 11, 14, 10, 17, 15 };        System.out.print(absSumDidd(arr));           }    // Contributed by Saurav Jain}
# Python3 program to find minimum sum of# absolute differences with an array element. # function to find min sum after operationdef absSumDidd(a, n):         # Sort the array    a.sort()         # Pick middle value    midValue = a[(int)(n // 2)]     # Sum of absolute differences.    sum = 0    for i in range(n):        sum = sum + abs(a[i] - midValue)    return sum # Driver Codearr = [5, 11, 14, 10, 17, 15]n = len(arr)print(absSumDidd(arr, n)) # This code is contributed# by sahishelangia
// C# program to find minimum sum of absolute// differences with an array element.using System;   class GFG {       // function to find min sum after operation    static int absSumDidd(int []a)    {        // Sort the array        Array.Sort(a);                   // Pick middle value        int midValue = a[a.Length / 2];           // Sum of absolute differences.        int sum = 0;        for (int i = 0; i < a.Length; i++) {            sum = sum + Math.Abs(a[i] - midValue);        }                  return sum;           }       // Driver Code    public static void Main()    {        int []arr = { 5, 11, 14, 10, 17, 15 };        Console.Write(absSumDidd(arr));            }    // Contributed by Subhadeep}
<?php// PHP program to find minimum// sum of absolute differences// with an array element. // function to find min sum// after operationfunction absSumDidd($a, $n){    // Sort the array    sort($a);         // Pick middle value    $midValue = $a[($n / 2)];     // Sum of absolute differences.    $sum = 0;    for ( $i = 0; $i < $n; $i++)    {        $sum = $sum + abs($a[$i] -               $midValue);    }         return $sum;    } // Driver Code$arr = array(5, 11, 14, 10, 17, 15 );$n = count($arr);echo absSumDidd($arr, $n); // This code is contributed// by anuj_67?>
<script> // Javascript program to find minimum sum of absolute// differences with an array element. // Function to find min sum after operationfunction absSumDidd(a){         // Sort the array    a.sort((a, b) => a - b);         // Pick middle value    var midValue = a[a.length / 2];     // Sum of absolute differences.    var sum = 0;    for(var i = 0; i < a.length; i++)    {        sum = sum + Math.abs(a[i] - midValue);    }    return sum;      } // Driver Codevar arr = [ 5, 11, 14, 10, 17, 15 ];document.write(absSumDidd(arr));  // This code is contributed by shikhasingrajput </script>
20
 
Time Complexity: O(n Log n) We can further optimize above solution to O(n) by using linear time algorithm for median finding. 
tufan_gupta2000
Mithun Kumar
vt_m
sahilshelangia
shikhasingrajput
median-finding
Technical Scripter 2018
Arrays
Sorting
Technical Scripter
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find sum of elements in a given array
Trapping Rain Water
Move all negative numbers to beginning and positive to end with constant extra space
Reversal algorithm for array rotation
Window Sliding Technique