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.
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 !=
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With