Suppose you are given a list L
of n
numbers and an integer k
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.