10

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?

PengOne
  • 47,332
  • 17
  • 126
  • 147
CommonMan
  • 3,760
  • 2
  • 20
  • 35

1 Answers1

17

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.

PengOne
  • 47,332
  • 17
  • 126
  • 147
  • after a bit of thinking i still don't see how your proof reduces subset-sum to OP's problem. – soulcheck Jan 18 '12 at 19:45
  • i mean, you essencially proved that having answer to subset sum one can answer OP's problem, not the other way around. – soulcheck Jan 18 '12 at 19:57
  • @soulcheck I'm still pondering whether they are truly equivalent. I believe the answer comes down to [this question I just asked](http://stackoverflow.com/questions/8916539/sum-subset-with-a-fixed-subset-size). – PengOne Jan 18 '12 at 19:59
  • @PengOne I am confused whether we can use sum-subset problem to find the set of size k which sums to T_k. What if there are multiple sets of different size that sums to T_k and one such set is of size k. Is there a way we can tweak the sum_subset problem to find if there exists a set of size k? – NPE Sep 06 '12 at 03:26
  • @PengOne Is there a solution approach for this question? I wrote a code following this approach but its churning the wrong output. My code: https://ideone.com/HadH3V – user248884 Sep 07 '18 at 14:07