We need to make all element equal in this problem and also find minimum cost. This problem can be solved in many was. Let describe author's solution.
Firstly, count the frequency of every element of the array. Let’s calculate the total sum of the array. Initialize two variable with 0. Let call them cur and tot.
Then, let's iterate every possible element i, from 1 to 1000000, for every i:
The minimum cost among every possible i is the answer.