Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference of all possible pairs of numbers in an array

Suppose I have a reverse-sorted list of doubles: {3, 2, 1}

I want to find the sum of all the positive differences between possible pairs of numbers.
In this case, that would be (3-2)+(3-1)+(2-1) = 4.

I know that going through all the pairs is an option, but this takes O(n^2) time. Any idea on a better algorithm?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is a very similar question that’s been answered, but I can’t quite find how to apply this to differences instead of sums.

>Solution :

The i-th element (with i = 0 .. n-1) in your sorted list will be

  • added to the sum n-i-1 times
  • substracted from the sum i times

So you can simply do

let sum = 0;
for (let i = 0; i < n; i++)
  sum = sum + (n-i-1) * list[i] - i * list[i]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading