Efficient algorithm to calculate the sum of all k-products

前端 未结 6 1934
青春惊慌失措
青春惊慌失措 2021-02-06 04:49

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

6条回答
  •  情歌与酒
    2021-02-06 05:31

    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

提交回复
热议问题