Sum of minimum absolute difference of each array element - GeeksforGeeks

14 Apr, 2021
Given an array of n distinct integers. The problem is to find the sum of minimum absolute difference of each array element. For an element x present at index i in the array its minimum absolute difference is calculated as: Min absolute difference (x) = min(abs(x – arr[j])), where 1 <= j <= n and j != i and abs is the absolute value. Input Constraint: 2 <= nExamples:  
Input : arr = {4, 1, 5}
Output : 5
Sum of absolute differences is |4-5| + |1-4| + |5-4|

Input : arr = {5, 10, 1, 4, 8, 7}
Output : 9

Input : {12, 10, 15, 22, 21, 20, 1, 8, 9}
Output : 18
 
Naive approach: Using two loops. Pick an element of the array using outer loop and calculate its absolute difference with rest of the array elements using inner loop. Find the minimum absolute value and add it to the sum. Time Complexity O(n2). Efficient Approach: The following steps are: 
Sort the array of size n.For the 1st element of array its min absolute difference is calculated using the 2nd array element.For the last array element its min absolute difference is calculated using the 2nd last array element.For the rest of the array elements, 1 <= i <= n-2, minimum absolute difference for an element at index i is calculated as: minAbsDiff = min( abs(arr[i] – arr[i-1]), abs(ar[i] – arr[i+1]) ).
Sort the array of size n.
For the 1st element of array its min absolute difference is calculated using the 2nd array element.
For the last array element its min absolute difference is calculated using the 2nd last array element.
For the rest of the array elements, 1 <= i <= n-2, minimum absolute difference for an element at index i is calculated as: minAbsDiff = min( abs(arr[i] – arr[i-1]), abs(ar[i] – arr[i+1]) ).
 
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to find the sum of minimum// absolute difference of each array element#include <bits/stdc++.h>using namespace std; // function to find the sum of// minimum absolute differenceint sumOfMinAbsDifferences(int arr[], int n){    // sort the given array    sort(arr, arr+n);         // initialize sum    int sum = 0;         // min absolute difference for    // the 1st array element    sum += abs(arr[0] - arr[1]);         // min absolute difference for    // the last array element    sum += abs(arr[n-1] - arr[n-2]);         // find min absolute difference for rest of the    // array elements and add them to sum    for (int i=1; i<n-1; i++)        sum += min(abs(arr[i] - arr[i-1]), abs(arr[i] - arr[i+1]));             // required sum       return sum;   } // Driver program to test aboveint main(){    int arr[] = {5, 10, 1, 4, 8, 7};    int n = sizeof(arr) / sizeof(arr[0]);    cout << "Sum = "         << sumOfMinAbsDifferences(arr, n);}
// java implementation to find the sum// of minimum absolute difference of// each array elementimport java.*;import java.util.Arrays; public class GFG {         // function to find the sum of    // minimum absolute difference    static int sumOfMinAbsDifferences(                         int arr[] ,int n)    {                 // sort the given array        Arrays.sort(arr);                 // initialize sum        int sum = 0;                 // min absolute difference for        // the 1st array element        sum += Math.abs(arr[0] - arr[1]);                 // min absolute difference for        // the last array element        sum += Math.abs(arr[n-1] - arr[n-2]);                 // find min absolute difference for        // rest of the array elements and        // add them to sum        for (int i = 1; i < n - 1; i++)            sum +=            Math.min(Math.abs(arr[i] - arr[i-1]),                    Math.abs(arr[i] - arr[i+1]));                     // required sum        return sum;    }         // Driver code    public static void main(String args[])    {        int arr[] = {5, 10, 1, 4, 8, 7};        int n = arr.length;                 System.out.println( "Sum = "        + sumOfMinAbsDifferences(arr, n));    }} // This code is contributed by Sam007.
# Python implementation to find the# sum of minimum absolute difference# of each array element # function to find the sum of# minimum absolute difference def sumOfMinAbsDifferences(arr,n):    # sort the given array    arr.sort()    # initialize sum    sum = 0             # min absolute difference for    # the 1st array element    sum += abs(arr[0] - arr[1]);             # min absolute difference for    # the last array element    sum += abs(arr[n - 1] - arr[n - 2]);             # find min absolute difference for    # rest of the array elements and    # add them to sum    for i in range(1, n - 1):        sum += min(abs(arr[i] - arr[i - 1]),                  abs(arr[i] - arr[i + 1]))                 # required sum    return sum;          # Driver codearr = [5, 10, 1, 4, 8, 7]n = len(arr)print( "Sum = ", sumOfMinAbsDifferences(arr, n))          #This code is contributed by Sam007
// C# implementation to find the sum// of minimum absolute difference of// each array elementusing System;         public class GFG {         // function to find the sum of    // minimum absolute difference    static int sumOfMinAbsDifferences(                         int []arr ,int n)    {                 // sort the given array        Array.Sort(arr);                 // initialize sum        int sum = 0;                 // min absolute difference for        // the 1st array element        sum += Math.Abs(arr[0] - arr[1]);                 // min absolute difference for        // the last array element        sum += Math.Abs(arr[n-1] - arr[n-2]);                 // find min absolute difference for        // rest of the array elements and        // add them to sum        for (int i = 1; i < n - 1; i++)            sum +=            Math.Min(Math.Abs(arr[i] - arr[i-1]),                    Math.Abs(arr[i] - arr[i+1]));                     // required sum        return sum;    }         // Driver code    public static void Main ()    {        int []arr = {5, 10, 1, 4, 8, 7};        int n = arr.Length;                 Console.Write( "Sum = "        + sumOfMinAbsDifferences(arr, n));    }} // This code is contributed by Sam007.
<?php// PHP implementation to find// the sum of minimum absolute// difference of each array element // function to find the sum of// minimum absolute differencefunction sumOfMinAbsDifferences($arr, $n){         // sort the given array    sort($arr);    sort( $arr,$n);         // initialize sum    $sum = 0;         // min absolute difference for    // the 1st array element    $sum += abs($arr[0] - $arr[1]);         // min absolute difference for    // the last array element    $sum += abs($arr[$n - 1] - $arr[$n - 2]);         // find min absolute difference    // for rest of the array elements    // and add them to sum    for ($i = 1; $i < $n - 1; $i++)        $sum += min(abs($arr[$i] - $arr[$i - 1]),                   abs($arr[$i] - $arr[$i + 1]));             // required sum    return $sum;}     // Driver Code    $arr = array(5, 10, 1, 4, 8, 7);    $n = sizeof($arr);    echo "Sum = ", sumOfMinAbsDifferences($arr, $n); // This code is contributed by nitin mittal.?>
<script>     // Javascript implementation to find the sum    // of minimum absolute difference of    // each array element         // function to find the sum of    // minimum absolute difference    function sumOfMinAbsDifferences(arr, n)    {                   // sort the given array        arr.sort(function(a, b){return a - b});                   // initialize sum        let sum = 0;                   // min absolute difference for        // the 1st array element        sum += Math.abs(arr[0] - arr[1]);                   // min absolute difference for        // the last array element        sum += Math.abs(arr[n-1] - arr[n-2]);                   // find min absolute difference for        // rest of the array elements and        // add them to sum        for (let i = 1; i < n - 1; i++)            sum +=            Math.min(Math.abs(arr[i] - arr[i-1]),                    Math.abs(arr[i] - arr[i+1]));                       // required sum        return sum;    }         let arr = [5, 10, 1, 4, 8, 7];    let n = arr.length;     document.write( "Sum = " + sumOfMinAbsDifferences(arr, n));     </script>
Output: 
Sum = 9
Time Complexity: O(nlogn)This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Sam007
nitin mittal
decode2207
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java