Sum of absolute differences of all pairs in a given array
Last Updated :
23 Apr, 2023
Given a sorted array of distinct elements, the task is to find the summation of absolute differences of all pairs in the given array.
Examples:
Input : arr[] = {1, 2, 3, 4}
Output: 10
Sum of |2-1| + |3-1| + |4-1| +
|3-2| + |4-2| + |4-3| = 10
Input : arr[] = {1, 8, 9, 15, 16}
Output: 74
Input : arr[] = {1, 2, 3, 4, 5, 7, 9, 11, 14}
Output: 188
A simple solution for this problem is to one by one look for each pair take their difference and sum up them together. The time complexity for this approach is O(n2).
C++
#include<bits/stdc++.h>
using namespace std;
int sumPairs( int arr[], int n)
{
int sum = 0;
for ( int i=0;i<n;i++)
{
for ( int j=i+1;j<n;j++)
{
sum+= abs (arr[i]-arr[j]);
}
}
return sum;
}
int main()
{
int arr[] = {1, 8, 9, 15, 16};
int n = sizeof (arr)/ sizeof (arr[0]);
cout << sumPairs(arr, n);
return 0;
}
|
Java
class GFG {
static int sumPairs( int arr[], int n)
{
int sum = 0 ;
for ( int i = 0 ; i < n; i++) {
for ( int j = i + 1 ; j < n; j++) {
sum += Math.abs(arr[i] - arr[j]);
}
}
return sum;
}
public static void main(String[] args)
{
int arr[] = { 1 , 8 , 9 , 15 , 16 };
int n = arr.length;
System.out.println(sumPairs(arr, n));
}
}
|
Python3
def sumPairs(arr, n):
sum = 0 ;
for i in range (n):
for j in range (i + 1 , n):
sum + = abs (arr[i] - arr[j]);
return sum ;
arr = [ 1 , 8 , 9 , 15 , 16 ];
n = len (arr);
print (sumPairs(arr, n));
|
C#
using System;
class GFG {
static int sumPairs( int [] arr, int n)
{
int sum = 0;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
sum += Math.Abs(arr[i] - arr[j]);
}
}
return sum;
}
public static void Main( string [] args)
{
int [] arr = { 1, 8, 9, 15, 16 };
int n = arr.Length;
Console.WriteLine(sumPairs(arr, n));
}
}
|
Javascript
function sumPairs(arr, n)
{
let sum = 0;
for ( var i=0;i<n;i++)
{
for ( var j=i+1;j<n;j++)
{
sum+= Math.abs(arr[i]-arr[j]);
}
}
return sum;
}
let arr = [1, 8, 9, 15, 16];
let n = arr.length;
console.log(sumPairs(arr, n));
|
The space complexity of this program is O(1), because it does not use any extra space that depends on the input size. The only space used is for the input array, which has a fixed size of n, so the space complexity is constant.
An efficient solution for this problem needs a simple observation. Since array is sorted and elements are distinct when we take sum of absolute difference of pairs each element in the i’th position is added ‘i’ times and subtracted ‘n-1-i’ times.
For example in {1,2,3,4} element at index 2 is arr[2] = 3 so all pairs having 3 as one element will be (1,3), (2,3) and (3,4), now when we take summation of absolute difference of pairs, then for all pairs in which 3 is present as one element summation will be = (3-1)+(3-2)+(4-3). We can see that 3 is added i = 2 times and subtracted n-1-i = (4-1-2) = 1 times.
The generalized expression for each element will be sum = sum + (i*a[i]) – (n-1-i)*a[i].
C++
#include<bits/stdc++.h>
using namespace std;
int sumPairs( int arr[], int n)
{
int sum = 0;
for ( int i=n-1; i>=0; i--)
sum += i*arr[i] - (n-1-i)*arr[i];
return sum;
}
int main()
{
int arr[] = {1, 8, 9, 15, 16};
int n = sizeof (arr)/ sizeof (arr[0]);
cout << sumPairs(arr, n);
return 0;
}
|
C
#include <stdio.h>
int sumPairs( int arr[], int n)
{
int sum = 0;
for ( int i = n - 1; i >= 0; i--)
sum += i * arr[i] - (n - 1 - i) * arr[i];
return sum;
}
int main()
{
int arr[] = { 1, 8, 9, 15, 16 };
int n = sizeof (arr) / sizeof (arr[0]);
printf ( "%d" , sumPairs(arr, n));
return 0;
}
|
Java
class GFG {
static int sumPairs( int arr[], int n)
{
int sum = 0 ;
for ( int i = n - 1 ; i >= 0 ; i--)
sum += i * arr[i] - (n - 1 - i) * arr[i];
return sum;
}
public static void main(String arg[])
{
int arr[] = { 1 , 8 , 9 , 15 , 16 };
int n = arr.length;
System.out.print(sumPairs(arr, n));
}
}
|
Python3
def sumPairs(arr, n):
sum = 0
for i in range (n - 1 , - 1 , - 1 ):
sum + = i * arr[i] - (n - 1 - i) * arr[i]
return sum
arr = [ 1 , 8 , 9 , 15 , 16 ]
n = len (arr)
print (sumPairs(arr, n))
|
C#
using System;
class GFG {
static int sumPairs( int []arr, int n)
{
int sum = 0;
for ( int i = n - 1; i >= 0; i--)
sum += i * arr[i] - (n - 1 - i)
* arr[i];
return sum;
}
public static void Main()
{
int []arr = { 1, 8, 9, 15, 16 };
int n = arr.Length;
Console.Write(sumPairs(arr, n));
}
}
|
PHP
<?php
function sumPairs( $arr , $n )
{
$sum = 0;
for ( $i = $n -1; $i >=0; $i --)
$sum = $sum + $i * $arr [ $i ] - ( $n -1- $i )* $arr [ $i ];
return $sum ;
}
$arr = array (1, 8, 9, 15, 16);
$n = sizeof( $arr )/sizeof( $arr [0]);
echo sumPairs( $arr , $n );
?>
|
Javascript
<script>
function sumPairs( arr, n)
{
let sum = 0;
for (let i=n-1; i>=0; i--)
sum += i*arr[i] - (n-1-i)*arr[i];
return sum;
}
let arr = [ 1, 8, 9, 15, 16 ];
let n = arr.length;
document.write(sumPairs(arr, n));
</script>
|
Time Complexity: O(n)
Auxiliary space: O(1)
What if array is not sorted?
The efficient solution is also better for the cases where array is not sorted. We can sort the array first in O(n Log n) time and then find the required value in O(n). So overall time complexity is O(n Log n) which is still better than O(n2)
Below is the code for above approach.
C++
#include<bits/stdc++.h>
using namespace std;
int sumPairs( int arr[], int n)
{
sort(arr, arr+n);
int sum = 0;
for ( int i = 0; i < n; i++){
sum += i*arr[i] - (n-1-i)*arr[i];
}
return sum;
}
int main()
{
int arr[] = {16, 8, 9, 1, 15};
int n = sizeof (arr)/ sizeof (arr[0]);
cout<<sumPairs(arr, n);
return 0;
}
|
Java
import java.util.Arrays;
public class Main {
static int sumPairs( int [] arr, int n) {
Arrays.sort(arr);
int sum = 0 ;
for ( int i = 0 ; i < n; i++) {
sum += i*arr[i] - (n- 1 -i)*arr[i];
}
return sum;
}
public static void main(String[] args) {
int [] arr = { 16 , 8 , 9 , 1 , 15 };
int n = arr.length;
System.out.println(sumPairs(arr, n));
}
}
|
Python3
def sumPairs(arr, n):
arr.sort()
sum = 0
for i in range (n):
sum + = i * arr[i] - (n - 1 - i) * arr[i]
return sum
arr = [ 16 , 8 , 9 , 1 , 15 ]
n = len (arr)
print (sumPairs(arr, n))
|
C#
using System;
class Program {
static int SumPairs( int [] arr, int n)
{
Array.Sort(arr);
int sum = 0;
for ( int i = 0; i < n; i++){
sum += i*arr[i] - (n-1-i)*arr[i];
}
return sum;
}
static void Main( string [] args) {
int [] arr = {16, 8, 9, 1, 15};
int n = arr.Length;
Console.WriteLine(SumPairs(arr, n));
}
}
|
Javascript
function sumPairs(arr, n) {
arr.sort((a, b) => a - b);
let sum = 0;
for (let i = 0; i < n; i++) {
sum += i*arr[i] - (n-1-i)*arr[i];
}
return sum;
}
let arr = [16, 8, 9, 1, 15];
let n = arr.length;
console.log(sumPairs(arr, n));
|
Time Complexity: O(n*log(n))
Auxiliary space: O(1)
Similar Reads
Product of absolute difference of every pair in given Array
Given an array arr[] of N elements, the task is to find the product of absolute differences of all pairs in the given array. Examples: Input: arr[] = {1, 2, 3, 4} Output: 12Explanation: Product of |2-1| * |3-1| * |4-1| * |3-2| * |4-2| * |4-3| = 12Input: arr[] = {1, 8, 9, 15, 16} Output: 27659520 App
4 min read
Minimum possible sum of absolute difference of pairs from given arrays
Given two arrays a[] and b[] of size N and M respectively (N < M), the task is to find the minimum possible sum of absolute difference of pairs formed by pairing each element of array a[] with an element of array b[] Note: Each element of each array can be considered only once. Examples: Input: a
8 min read
Minimum sum of absolute difference of pairs of two arrays
Given two arrays a[] and b[] of equal length n. The task is to pair each element of array a to an element in array b, such that sum S of absolute differences of all the pairs is minimum.Suppose, two elements a[i] and a[j] (i != j) of a are paired with elements b[p] and b[q] of b respectively, then p
7 min read
Minimum and Maximum sum of absolute differences of pairs
Given an array of N integers where N is even, find the minimum and maximum sum of absolute difference of N/2 pairs formed by pairing every element with one other element. Examples: Input: a[] = {10, -10, 20, -40} Output: min_sum = 40, max_sum = 80 Explanation: Pairs selected for minimum sum (-10, -4
8 min read
Minimum sum of absolute differences of pairs in a triplet from three arrays
Given three arrays a[], b[] and c[] of sizes A, B and C respectively, the task is to find the minimum possible value of abs(a[i] - b[j]) + abs(b[j] - c[k]) where 0 ? i ? A, 0 ? j ? B and 0 ? k ? C. Examples: Input: A = 3, B = 2, C = 2, a[] = {1, 8, 5}, b[] = {2, 9}, c[] = {5, 4}Output: 3Explanation:
11 min read
Count of all pairs in an Array with minimum absolute difference
Given an integer array arr[] of size N, the task is to count the total number of distinct pairs having minimum absolute difference. Examples: Input: arr[] = {4, 2, 1, 3} Output: 3 Explanation: The minimum absolute difference between the pairs {1, 2}, {2, 3}, {3, 4} is 1.Input: arr[] = {1, 3, 8, 10,
5 min read
Minimum sum of absolute differences between pairs of a triplet from an array
Given an array A[] consisting of positive integers, the task is to find the minimum value of |A[x] - A[y]| + |A[y] - A[z]| of any triplet (A[x], A[y], A[z]) from an array. Examples: Input: A[] = { 1, 1, 2, 3 }Output: 1Explanation:For x = 0, y = 1, z = 2|A[x] - A[y]| + |A[y] - A[z]| = 0 + 1 = 1, whic
5 min read
Sum of minimum absolute difference of each array element
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 <
8 min read
Minimum value of maximum absolute difference of all adjacent pairs in an Array
Given an array arr, containing non-negative integers and (-1)s, of size N, the task is to replace those (-1)s with a common non-negative integer such that the maximum absolute difference of all adjacent pairs is minimum. Print this minimum possible value of the maximum absolute difference. Examples:
9 min read
Find maximum absolute difference with min sum of ratios in an Array
Given an array of positive integers arr[], the task is to find the maximum absolute difference between the pairs from the array such that the sum of their ratios is minimum. Examples: Input: arr[] = {2, 6, 3, 4, 8, 9}Output: 4Explanation: In the above example, the ratios of every pair are calculated
7 min read