Let’s formalize the problem. Suppose you’re given an array read from the input.
Operation #1: Pick some coins from any pile and put them back in Chef’s coin box.
This means we can decrease the number of coins from any pile.
Operation #2: Pick some coins from the Chef’s coin box and put them on any one pile.
This means we can increase the number of coins from any pile.
Observations #1 and #2 combined tell us we can change the number of conins from any pile to what number we want. Our goal is to have the same value in each pile.
The trick is to find the most frequent value and make all array equal to that value.
Picking the most frequent value
So you get an array and you can change what element you want. What’s the minimal number of changes in order to get all elements equal?
Denote x as the value in the array after we finish all operations. Obviously, x must be a value from the initial array. A brute force algorithm could be taking 1st element, 2nd element, …, nth element and assume it is x. Then, calculate the cost and pick the minimal cost. However, this takes O(n ^ 2), which is too much for get full score.
Let’s try something else. After we pick an x, the cost is equal to number of elements that have different value from x. This cost is also n - number of elements that have the same value with x. Since n is constant, we need to minimize expression: (-(number of elements that have the same value with x)), or maximize the expression (number of elements that have same value with x). (We got this considering that if -a is minimized, then a will be maximized).
So maximizing number of elements that have the same value with x can be done by finding the most frequent element from the array.
Finding the most frequent element of the array
We’ll present two ways to get it:
First way is based on the small values for A[i] elements. We can keep an array count[x] = how many times does value x appear in the array. Then, we can iterate elements of count from 0 to 10^5 (the upper limit for A[i]) and store the maximum.
The second way is based on the fact that elements having the same value form a contiguous subsequence in the sorted array. So we sort our array and divide it in “blocks” having the same value. An element x will appear in exactly one block of elements having the same value. This approach can be used to solve the problem even if we’re not given A[i] <= 10^5 restriction.
Depending on how you implement it, the complexity is either O(n + maximumValue) or O(n * log(n)).