Sum of products of elements of all subarrays of length k

前端 未结 2 461
情深已故
情深已故 2021-01-02 20:51

An array of length n is given. Find the sum of products of elements of the sub-array.

Explanation

Array A

相关标签:
2条回答
  • 2021-01-02 21:43

    There is rather simple way:
    Construct product of terms (1 + A[i] * x):

    P = (1 + A[0] * x) * (1 + A[1] * x) * (1 + A[2] * x)...*(1 + A[n-1] * x)
    

    If we open the brackets, then we'll get polynomial

    P = 1 + B[1] * x + B[2] * x^2 + ... + B[n] * x^n
    

    Kth coefficient, B[k], is equal to the sum of products of sets with length K - for example, B[n] = A[0]*A[1]*A[2]*..A[n-1], B[2] = A[0]*A[1] + A[0]*A[2] + ... + A[n-2]*A[n-1] and so on.

    So to find sum of products of all possible sets, we have to find value of polynomial P for x = 1, then subtract 1 to remove leading 0th term. If we don't want to take into consideration single-element sets, then subtract B1 = sum of A[i].

    Example:

    (1+2)(1+3)(1+4) = 60
    60 - 1 = 59
    59 - (2 + 3 + 4) = 50 = 24 + 26 - as your example shows
    
    0 讨论(0)
  • 2021-01-02 21:52

    We first create a recursive relation. Let f(n, k) be the sum of all products of sub-arrays of length k from an array a of length n. The base cases are simple:

    f(0, k) = 0 for all k
    f(n, 0) = 1 for all n
    

    The second rule might seem a little counter-intuitive, but 1 is the zero-element of multiplication.

    Now we find a recursive relation for f(n+1, k). We want the product of all subarrays of size k. There are two types of subarrays here: the ones including a[n+1] and the ones not including a[n+1]. The sum of the ones not including a[n+1] is exactly f(n, k). The ones including a[n+1] are exactly all subarrays of length k-1 with a[n+1] added, so their summed product is a[n+1] * f(n, k-1).

    This completes our recurrence relation:

    f(n, k) = 0                               if n = 0
            = 1                               if k = 0
            = f(n-1, k) + a[n] * f(n-1, k-1)  otherwise
    

    You can use a neat trick to use very limited memory for your dynamic programming, because function f only depends on two earlier values:

    int[] compute(int[] a) {
        int N = a.length;
        int[] f = int[N];
        f[0] = 1;
    
        for (int n = 1; n < N; n++) {
            for (int k = n; k >= 1; k--) {
                f[k] = (f[k] + a[n] * f[k-1]) % 1000000007;
            }
        }
    
        return f;
    }
    
    0 讨论(0)
提交回复
热议问题