简体   繁体   中英

Sum of all possible pairs of elements in an array

I was trying to solve problem, where an array of integers is given, I need to find sum of all possible pairs of elements in an given array. For example array is 1,2,3,4 then it should give 1+2 + 1+3 + 1+4 + 2+3 + 2+4 + 3+4 = 30

Now, I tried different things but I can not come with any algorithm having complexity less than O(n^2). Does anybody have an idea about a algorithm with complexity less than O(n^2)

Since every element of the array occurs in exactly n-1 pairs, sum all of them up and multiply by n-1 , which means this is O(n) .


This actually generalizes to the case where you need the sum of the sums of all k-element multisets. In that case, every element of the array appears in exactly (n-1) choose (k-1) multisets, so add them all up and multiply by that. The calculation of the binomial coefficient may become a bit much at some point, but definitely beats enumerating all k-element multisets and adding them up.

Unless you know something about the values in the array, I don't see any way to do it that isn't O(n^2).

The number of combinations of N items taken 2 at a time is:

N           C
10          45
100       4950
1000    499500

As you can see, the number of combinations is approximately (N^2)/2 so I don't see how you can do better than that without extra information.

In c++ there is a function called next_permutation() which generates next 'combination' of elements in array. So you can do something like this:

int A=[1,2,3,4,5];
while(next_permutation(A,A+5)) //NOTE: A is pointer to first element of array A
{
    // do something
}

If you get the idea, you should be able to customize code for your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM