Efficient algorithm to calculate the sum of all k-products

前端 未结 6 1936
青春惊慌失措
青春惊慌失措 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:29

    An interesting property you could explore is the distributive property of multiplication in relation to addition.

    L=[a,b,c,d]
    

    When k = 1, it's trivial:

    S=a+b+c+d
    

    When k = 2:

    S = a * (b + c + d) + b * (c + d) + c * d
    

    When k = 3, things get a bit more interesting:

    S = a * b * ( c + d) + (c * d) * (a + b)
    S = a * (b * (c + d)) + c * d) + b * (c * d)  <-- this form lends itself better to the algorithm
    

    And for k = 4:

    S = a * b * c * d
    

    This should hold for larger values of n.

    An implementation in C#:

     private static int ComputeSum(int[] array, int offset, int K)
     {
         int S = 0;
    
         if (K == 1)
         {                      
             for (int i = offset; i < array.Length; i++)
                 S += array[i];
         }
         else if ((array.Length - offset) == K)
         {
             S = array[offset] * ComputeSum(array, offset + 1, K - 1);
         }
         else if (offset < array.Length)
         {
             S = ComputeSum(array, offset + 1, K) + array[offset] * ComputeSum(array, offset + 1, K - 1);             
         }
    
         return S;
     }
    

    Which can be further improved by memoization.

提交回复
热议问题