-1

You are given an array of positive integers. You are told to make all the numbers equal by doing this operation, i.e. to increase/decrease the value of an array element. The cost of the operation will be the amount of increment/decrement (absolute value). Find the minimum cost required to do this task.

Test Example
Array : 2 3 1 5 2
Answer : 5

At first, it appears as though we should change all values to mean value and that should do the trick. But the optimal answer comes when using the median value. I understand that the mean is more sensitive to outliers but still, I cannot really understand why would changing values to the mean value will not give an optimal answer.

Anant
  • 302
  • 2
  • 11

1 Answers1

0

Suppose you decide to change each array element to v. The cost of changing a[i] to v is

|a[i] - v|

So the total cost is

C(v) = Sum{ i | |a[i]-v| }

We want to chose v to minimise the total cost. The v that does that is a median for the a[]. The proof of that is a little awkward, in the general case... However if you consider a list with every element unique you should be able to convince yourself in that case.

By contrast the mean m is what minimises

Sum{ (a[i]-m)*(a[i]-m)}

So that the mean would be the choice for a problem where you could add any number to an element, the cost being the square of what what you added. The proof that the mean minimises is easy.

dmuir
  • 4,211
  • 2
  • 14
  • 12