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?
How do you partition an array into 2 parts such that the two parts
Share
You can reduce this problem to the sum-subset problem – also cached here. Here’s the idea.
Let
Abe the array. ComputeS = A[0] + ... + A[N-1], whereNis the length ofA. Forkfrom1toN-1, letT_k = S * k / N. IfT_kis an integer, then find a subset ofAof sizekthat sums toT_k. If you can do this, then you’re done. If you cannot do this for anyk, then no such partitioning exists.Here’s the math behind this approach. Suppose there is a partitioning of
Asuch that the two parts have the same average, saysXof sizexandYof sizeyare the partitions, wherex+y = N. Then you must haveso a bit of algebra gives
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 / Nmust be an integer. The only remaining part is to realizeT_kas the sum of a subset of sizek.