Open In App

# Sum of minimum absolute difference of each array element

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 <= n

Examples:

```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```
Recommended Practice

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).

## C++

 `// C++ implementation to find the sum``// of minimum absolute difference of``// each array element``#include ``using` `namespace` `std;` `// function to find the sum of``// minimum absolute difference``int` `sumOfMinAbsDifferences(``int` `arr[], ``int` `n)``{``  ``int` `sum = 0;``  ``for` `(``int` `i = 0; i < n; i++) {``    ``int` `diff = INT_MAX;``    ``for` `(``int` `j = 0; j < n; j++) {``      ``if` `(i != j) {``        ``diff = min(diff, ``abs``(arr[i] - arr[j]));``      ``}``    ``}``    ``sum += diff;``  ``}``  ` `  ``// required sum``  ``return` `sum;``}` `// Driver code``int` `main()``{``  ``int` `arr[] = { 5, 10, 1, 4, 8, 7 };``  ``int` `n = 6;` `  ``cout << ``"Sum = "` `<< sumOfMinAbsDifferences(arr, n);``}` `// This code is contributed by garg28harsh.`

## Java

 `// java implementation to find the sum``// of minimum absolute difference of``// each array element` `import` `java.util.*;``import` `java.io.*;``public` `class` `GFG {``    ` `    ``// function to find the sum of``    ``// minimum absolute difference``    ``static` `int` `sumOfMinAbsDifferences(``                        ``int` `arr[] ,``int` `n)``    ``{``        ``int` `sum=``0``;``      ``for``(``int` `i=``0``;i

## Python3

 `# Python3 implementation to find the sum``# of minimum absolute difference of``# each array element``import` `sys` `# function to find the sum of``# minimum absolute difference``def` `sumOfMinAbsDifferences(arr, n):``    ``sum` `=` `0``    ``for` `i ``in` `range``(n):``        ``diff ``=` `sys.maxsize``        ``for` `j ``in` `range``(n):``            ``if` `i !``=` `j:``                ``diff ``=` `min``(diff, ``abs``(arr[i] ``-` `arr[j]))``        ``sum` `+``=` `diff``  ` `    ``# required sum``    ``return` `sum` `# Driver code``if` `__name__ ``=``=` `"__main__"``:``    ``arr ``=` `[``5``, ``10``, ``1``, ``4``, ``8``, ``7``]``    ``n ``=` `6` `    ``print``(``"Sum ="``, sumOfMinAbsDifferences(arr, n))` `# This code is contributed by akashish__`

## C#

 `// Include namespace system``using` `System;` `public` `class` `GFG``{``  ``// function to find the sum of``  ``// minimum absolute difference``  ``public` `static` `int` `sumOfMinAbsDifferences(``int``[] arr, ``int` `n)``  ``{``    ``var` `sum = 0;``    ``for` `(``int` `i = 0; i < n; i++)``    ``{``      ``var` `diff = ``int``.MaxValue;``      ``for` `(``int` `j = 0; j < n; j++)``      ``{``        ``if` `(i != j)``        ``{``          ``diff = Math.Min(diff,Math.Abs(arr[i] - arr[j]));``        ``}``      ``}``      ``sum += diff;``    ``}``    ``// required sum``    ``return` `sum;``  ``}` `  ``// Driver code``  ``public` `static` `void` `Main(String[] args)``  ``{``    ``int``[] arr = {5, 10, 1, 4, 8, 7};``    ``var` `n = arr.Length;``    ``Console.WriteLine(``"Sum = "` `+ GFG.sumOfMinAbsDifferences(arr, n).ToString());``  ``}``}` `// This code is contributed by aadityaburujwale.`

## Javascript

 `// 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)``{``    ``let sum = 0;``    ``for` `(let i = 0; i < n; i++) {``        ``let diff = Number.MAX_VALUE;``        ``for` `(let j = 0; j < n; j++) {``            ``if` `(i != j) {``                ``diff = Math.min(diff,``                                ``Math.abs(arr[i] - arr[j]));``            ``}``        ``}``        ``sum += diff;``    ``}` `    ``// required sum``    ``return` `sum;``}` `// Driver code``let arr = [ 5, 10, 1, 4, 8, 7 ];``let n = 6;` `console.log(``"Sum = "` `+ sumOfMinAbsDifferences(arr, n));` `// This code is contributed by garg28harsh.`

Output

`Sum = 9`

Time Complexity: O(n2) where n is size of the input array. This is because two nested loops are executing.

Space Complexity: O(1) as  no extra space has been used.

Efficient Approach:

The following steps are:

1. Sort the array of size n.
2. For the 1st element of array its min absolute difference is calculated using the 2nd array element.
3. For the last array element its min absolute difference is calculated using the 2nd last array element.
4. 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]) ).

Implementation:

## C++

 `// C++ implementation to find the sum of minimum``// absolute difference of each array element``#include ``using` `namespace` `std;` `// function to find the sum of``// minimum absolute difference``int` `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

## Java

 `// java implementation to find the sum``// of minimum absolute difference of``// each array element``import` `java.io.*;``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.`

## Python3

 `# 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 code``arr ``=` `[``5``, ``10``, ``1``, ``4``, ``8``, ``7``]``n ``=` `len``(arr)``print``( ``"Sum = "``, sumOfMinAbsDifferences(arr, n))``    ` `    ` `#This code is contributed by Sam007`

## C#

 `// C# implementation to find the sum``// of minimum absolute difference of``// each array element``using` `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

 ``

## Javascript

 ``

Output

`Sum = 9`

Time Complexity: O(n log n)
Auxiliary Space: O(1)

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.