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++
// C++ program to find sum of absolute differences
// in all pairs in a sorted array of distinct numbers
#include<bits/stdc++.h>
using namespace std;
// Function to calculate sum of absolute difference
// of all pairs in array
// arr[] --> array of elements
int sumPairs(int arr[],int n)
{
// final result
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;
}
// Driver program to run the case
int main()
{
int arr[] = {1, 8, 9, 15, 16};
int n = sizeof(arr)/sizeof(arr[0]);
cout << sumPairs(arr, n);
return 0;
}
// This code is contributed by Pushpesh Raj.
Java
// Java program to find sum of absolute differences
// in all pairs in a sorted array of distinct numbers
class GFG {
// Function to calculate sum of absolute difference
// of all pairs in array
// arr[] --> array of elements
static int sumPairs(int arr[], int n)
{
// final result
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;
}
// Driver program to run the case
public static void main(String[] args)
{
int arr[] = { 1, 8, 9, 15, 16 };
int n = arr.length;
System.out.println(sumPairs(arr, n));
}
}
// This code is contributed by karandeep1234.
Python3
# Python3 program to find sum of absolute differences
# in all pairs in a sorted array of distinct numbers
# Function to calculate sum of absolute difference
# of all pairs in array
# arr[] --> array of elements
def sumPairs(arr, n):
# final result
sum = 0;
for i in range(n):
for j in range(i + 1, n):
sum += abs(arr[i]-arr[j]);
return sum;
# Driver program to run the case
arr = [1, 8, 9, 15, 16];
n = len(arr);
print(sumPairs(arr, n));
# This code is contributed by phasing17
C#
// C# program to find sum of absolute differences
// in all pairs in a sorted array of distinct numbers
using System;
class GFG {
// Function to calculate sum of absolute difference
// of all pairs in array
// arr[] --> array of elements
static int sumPairs(int[] arr, int n)
{
// final result
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;
}
// Driver program to run the case
public static void Main(string[] args)
{
int[] arr = { 1, 8, 9, 15, 16 };
int n = arr.Length;
Console.WriteLine(sumPairs(arr, n));
}
}
// This code is contributed by phasing17.
JavaScript
// JS program to find sum of absolute differences
// in all pairs in a sorted array of distinct numbers
// Function to calculate sum of absolute difference
// of all pairs in array
// arr[] --> array of elements
function sumPairs(arr, n)
{
// final result
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;
}
// Driver program to run the case
let arr = [1, 8, 9, 15, 16];
let n = arr.length;
console.log(sumPairs(arr, n));
// This code is contributed by phasing17
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++
// C++ program to find sum of absolute differences
// in all pairs in a sorted array of distinct numbers
#include<bits/stdc++.h>
using namespace std;
// Function to calculate sum of absolute difference
// of all pairs in array
// arr[] --> array of elements
int sumPairs(int arr[],int n)
{
// final result
int sum = 0;
for (int i=n-1; i>=0; i--)
sum += i*arr[i] - (n-1-i)*arr[i];
return sum;
}
// Driver program to run the case
int main()
{
int arr[] = {1, 8, 9, 15, 16};
int n = sizeof(arr)/sizeof(arr[0]);
cout << sumPairs(arr, n);
return 0;
}
// This code is contributed by Sania Kumari Gupta
C
// C program to find sum of absolute differences
// in all pairs in a sorted array of distinct numbers
#include <stdio.h>
// Function to calculate sum of absolute difference
// of all pairs in array
// arr[] --> array of elements
int sumPairs(int arr[], int n)
{
// final result
int sum = 0;
for (int i = n - 1; i >= 0; i--)
sum += i * arr[i] - (n - 1 - i) * arr[i];
return sum;
}
// Driver program to run the case
int main()
{
int arr[] = { 1, 8, 9, 15, 16 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d", sumPairs(arr, n));
return 0;
}
// This code is contributed by Sania Kumari Gupta
Java
// Java program to find sum of absolute differences in all
// pairs in a sorted array of distinct numbers
class GFG {
// Function to calculate sum of absolute
// difference of all pairs in array
// arr[] --> array of elements
static int sumPairs(int arr[], int n)
{
// final result
int sum = 0;
for (int i = n - 1; i >= 0; i--)
sum += i * arr[i] - (n - 1 - i) * arr[i];
return sum;
}
// Driver program
public static void main(String arg[])
{
int arr[] = { 1, 8, 9, 15, 16 };
int n = arr.length;
System.out.print(sumPairs(arr, n));
}
}
// This code is contributed by Sania Kumari Gupta
Python3
# Python3 program to find sum of
# absolute differences in all pairs
# in a sorted array of distinct numbers
# Function to calculate sum of absolute
# difference of all pairs in array
# arr[] --> array of elements
def sumPairs(arr, n):
# final result
sum = 0
for i in range(n - 1, -1, -1):
sum += i*arr[i] - (n-1-i) * arr[i]
return sum
# Driver program
arr = [1, 8, 9, 15, 16]
n = len(arr)
print(sumPairs(arr, n))
# This code is contributed by Anant Agarwal.
C#
// C# program to find sum of absolute
// differences in all pairs in a sorted
// array of distinct numbers
using System;
class GFG {
// Function to calculate sum of absolute
// difference of all pairs in array
// arr[] --> array of elements
static int sumPairs(int []arr, int n)
{
// final result
int sum = 0;
for (int i = n - 1; i >= 0; i--)
sum += i * arr[i] - (n - 1 - i)
* arr[i];
return sum;
}
// Driver program
public static void Main()
{
int []arr = { 1, 8, 9, 15, 16 };
int n = arr.Length;
Console.Write(sumPairs(arr, n));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to find sum of absolute differences
// in all pairs in a sorted array of distinct numbers
// Function to calculate sum of absolute difference
// of all pairs in array
// arr[] --> array of elements
function sumPairs($arr,$n)
{
// final result
$sum = 0;
for ($i=$n-1; $i>=0; $i--)
$sum = $sum + $i*$arr[$i] - ($n-1-$i)*$arr[$i];
return $sum;
}
// Driver program to run the case
$arr = array(1, 8, 9, 15, 16);
$n = sizeof($arr)/sizeof($arr[0]);
echo sumPairs($arr, $n);
?>
JavaScript
<script>
// JavaScript program to find
// sum of absolute differences
// in all pairs in a sorted array
// of distinct numbers
// Function to calculate sum of absolute difference
// of all pairs in array
// arr[] --> array of elements
function sumPairs( arr, n)
{
// final result
let sum = 0;
for (let i=n-1; i>=0; i--)
sum += i*arr[i] - (n-1-i)*arr[i];
return sum;
}
// Driver program to run the case
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++
// C++ program for above approach
#include<bits/stdc++.h>
using namespace std;
// Function to calculate sum of absolute
// difference of all pairs in array
int sumPairs(int arr[], int n)
{
// sorting the array
sort(arr, arr+n);
// Initialising the variable
// to store the sum
int sum = 0;
// Iterating through each element
// and adding it i times and
// subtracting it (n-1-i) times
for(int i = 0; i < n; i++){
sum += i*arr[i] - (n-1-i)*arr[i];
}
return sum;
}
// Driver program
int main()
{
int arr[] = {16, 8, 9, 1, 15};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<sumPairs(arr, n);
return 0;
}
Java
// Java program for above approach
import java.util.Arrays;
public class Main {
// Function to calculate sum of absolute
// difference of all pairs in array
static int sumPairs(int[] arr, int n) {
// sorting the array
Arrays.sort(arr);
// Initialising the variable
// to store the sum
int sum = 0;
// Iterating through each element
// and adding it i times and
// subtracting it (n-1-i) times
for(int i = 0; i < n; i++) {
sum += i*arr[i] - (n-1-i)*arr[i];
}
return sum;
}
// Driver program
public static void main(String[] args) {
int[] arr = {16, 8, 9, 1, 15};
int n = arr.length;
System.out.println(sumPairs(arr, n));
}
}
// This code is contributed by bhardwajji
Python3
# Python program for above approach
# Function to calculate sum of absolute
# difference of all pairs in array
def sumPairs(arr, n):
# sorting the array
arr.sort()
# Initialising the variable
# to store the sum
sum = 0
# Iterating through each element
# and adding it i times and
# subtracting it (n-1-i) times
for i in range(n):
sum += i*arr[i] - (n-1-i)*arr[i]
return sum
# Driver program
arr = [16, 8, 9, 1, 15]
n = len(arr)
print(sumPairs(arr, n))
# This code is contributed by Aman Kumar.
C#
using System;
class Program {
// Function to calculate sum of absolute
// difference of all pairs in array
static int SumPairs(int[] arr, int n)
{
// sorting the array
Array.Sort(arr);
// Initialising the variable
// to store the sum
int sum = 0;
// Iterating through each element
// and adding it i times and
// subtracting it (n-1-i) times
for(int i = 0; i < n; i++){
sum += i*arr[i] - (n-1-i)*arr[i];
}
return sum;
}
// Driver program
static void Main(string[] args) {
int[] arr = {16, 8, 9, 1, 15};
int n = arr.Length;
Console.WriteLine(SumPairs(arr, n));
}
}
// This code is contributed by divyansh2212
JavaScript
// JavaScript program for above approach
// Function to calculate sum of absolute
// difference of all pairs in array
function sumPairs(arr, n) {
// sorting the array
arr.sort((a, b) => a - b);
// Initialising the variable
// to store the sum
let sum = 0;
// Iterating through each element
// and adding it i times and
// subtracting it (n-1-i) times
for (let i = 0; i < n; i++) {
sum += i*arr[i] - (n-1-i)*arr[i];
}
return sum;
}
// Driver code
let arr = [16, 8, 9, 1, 15];
let n = arr.length;
console.log(sumPairs(arr, n));
// This code is contributed by phasing17
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 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
Sum of minimum absolute differences in an array
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 <
7 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 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
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
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