Suppose I have an array {1, 2, 5, 4} and m = 3.
I need to find:
1*2*5 + 1*2*4 + 1*5*4 + 2*5*4
i.e Sum of multipli
This problem is equivalent to calculation of Mth coefficient of polynom with given roots (Vieta's theorem). Adapted algorithm in Delphi (O(N) memory and O(N^2) time):
function CalcMultiComb(const A: array of Integer; const M: Integer): Integer;
var
i, k, N: Integer;
Coeff: TArray;
begin
N := Length(A);
if (N = 0) or (M > N) then
Exit;
SetLength(Coeff, N + 1);
Coeff[0] := -A[0];
Coeff[1] := 1;
for k := 2 to N do begin
Coeff[k] := 1;
for i := k - 2 downto 0 do
Coeff[i + 1] := Coeff[i] - A[k-1] * Coeff[i + 1];
Coeff[0] := -A[k-1] * Coeff[0];
end;
Result := Coeff[N - M];
if Odd(N - M) then
Result := - Result;
end;
calls CalcMultiComb([1, 2, 3, 4], M) with M=1..4 give results 10, 35, 50, 24