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