Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient algorithm to calculate the sum of all k-products

Suppose you are given a list L of n numbers and an integer k<n. Is there an efficient way to calculate the sum of all products of k distinct numbers in L?

As an example, take L=[1,3,4,6] and k=2. Then the number I am looking for is

1*3 + 1*4 + 1*6 + 3*4 + 3*6 + 4*6.

Can you think of a way of doing it which avoids generating all the subsets of size k?

like image 368
mitchus Avatar asked Feb 14 '12 16:02

mitchus


1 Answers

Let F(X,k,n) be the k-product sum of first n elements of array X.

F(X,k,n) = F(X,k,n-1)+F(X,k-1,n-1)*X[n]

which you can solve using dynamic programming. Complexity = O(kn).

End conditions for F(X,k,n): When n=k F(X,k,k) = X[1]* X[2]*...*X[n]

More details:

F(X,1,1) = X[1]
F(X,1,i) = F(X,1,i-1)+X[i] for i=2...n 

For j=2..n:
    For i = 1..k:
        if i<j:
            F(X,i,j) = F(X,i,j-1)+F(X,i-1,j-1)*X[j]
        else if i==j:
            F(X,i,j) = F(X,i-1,j-1)*X[j]
        else:
            pass
like image 118
ElKamina Avatar answered Oct 17 '22 23:10

ElKamina