Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you partition an array into 2 parts such that the two parts have equal average?

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?

like image 518
CommonMan Avatar asked Jan 18 '12 17:01

CommonMan


People also ask

Can array be divided into two equal halves?

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.


1 Answers

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.

like image 113
PengOne Avatar answered Sep 28 '22 06:09

PengOne