Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding sum of Absolute Difference of Every pair of integer from an array

Tags:

algorithm

Given an array, find the sum of the absolute difference of every pair of integers.

For example: Given a[]= {2,3, 5, 7 };

output would be (3-2) + (5-2) + (7-2) + (5-3) + (7-3) + (7-5) = 17.

It must be done better than O(n^2).

The original array isn't necessarily sorted.

like image 687
Shamim Hafiz - MSFT Avatar asked May 02 '11 08:05

Shamim Hafiz - MSFT


People also ask

How do you find the absolute difference in an array?

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

How do you find the sum of absolute differences?

In digital image processing, the sum of absolute differences (SAD) is a measure of the similarity between image blocks. It is calculated by taking the absolute difference between each pixel in the original block and the corresponding pixel in the block being used for comparison.

How do you find the difference between two consecutive elements in an array?

To compute the differences between consecutive elements of a masked array, use the MaskedArray. ediff1d() method in Python Numpy. The "to_begin" parameter sets the number(s) to prepend at the beginning of the returned differences. This function is the equivalent of numpy.


2 Answers

note you add each number exactly k times (where k is its place if you sort the list)
also, you subtract each number exactly n-1-k times
you can sort the list (O(nlogn)) and then iterate over the sorted array, multiplying each element as mentioned above.

like image 95
amit Avatar answered Sep 28 '22 11:09

amit


I think I have found the answer. I got it by looking into the result expression in my post.

Here is the code in C++.

    int AbsDiff(int a[], int n)
    {
      if ( n < 2 ) return 0;
      sort(a,a+n);     
      int sum = 0;
      int i;
      for(i=n-1;i>=0;i--)
      {
        sum += (a[i]*(i) - a[i]*(n-i-1));
      }
      return sum;
    }
like image 34
Shamim Hafiz - MSFT Avatar answered Sep 28 '22 12:09

Shamim Hafiz - MSFT