How do you partition an array into 2 parts such that the two parts have equal average? Each partition may contain elements that are non-contiguous in the array. The only alg
You can reduce this problem to the sum-subset problem - also cached here. Here's the idea.
Let A
be the array. Compute S = A[0] + ... + A[N-1]
, where N
is the length of A
. For k
from 1
to N-1
, let T_k = S * k / N
. If T_k
is an integer, then find a subset of A
of size k
that sums to T_k
. If you can do this, then you're done. If you cannot do this for any k
, then no such partitioning exists.
Here's the math behind this approach. Suppose there is a partitioning of A
such that the two parts have the same average, says X
of size x
and Y
of size y
are the partitions, where x+y = N
. Then you must have
sum(X)/x = sum(Y)/y = (sum(A)-sum(X)) / (N-x)
so a bit of algebra gives
sum(X) = sum(A) * x / N
Since the array contains integers, the left hand side is an integer, so the right hand side must be as well. This motivates the constraint that T_k = S * k / N
must be an integer. The only remaining part is to realize T_k
as the sum of a subset of size k
.