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
?
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
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