Suppose you are given a list L
of n
numbers and an integer k
Algebraically, for k=2
just take the sum of the elements of L
, square it, and subtract the sum of the squares of L
. That is:
int sum = 0;
int sqSum = 0;
for (int i=0; i
In your example, what you are computing is this
(1 + 3 + 4 + 6)^2 - (1^2 + 3^2 + 4^2 + 6^2) = 1*3 + 1*4 + 1*6 + 3*4 + 3*6 + 4*6
This should give you a hint for how to proceed in general.