Sum of products of elements of all subarrays of length k

前端 未结 2 476
情深已故
情深已故 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: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;
    }
    

提交回复
热议问题