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 algorithm I can think of is exponential can we do better?
You can't always split the array equally. Here in this array, you can't partition array into more than 2 subparts, otherwise it will give more than 3 parts as some of the elements are present there having sum more than the partitioned Sum. Save this answer.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With