#K42307. Minimum Cost to Make List Elements Equal
Minimum Cost to Make List Elements Equal
Minimum Cost to Make List Elements Equal
You are given one or more test cases. For each test case, you are given a list of n integers. Your task is to determine the minimum total cost required to make all elements equal. You can change the value of an element at a cost equal to the absolute difference between its original value and the target value.
The optimal strategy is to choose the median of the list as the target value. In other words, if the list is sorted, let \( m \) be the median element. Then the minimum cost is computed as:
[ \text{cost} = \sum_{i=1}^{n} |a_i - m| ]
This approach minimizes the sum of absolute differences.
inputFormat
The input is read from standard input (stdin) and has the following format:
T N_1 a_1 a_2 ... a_(N1) N_2 b_1 b_2 ... b_(N2) ... N_T ... (list of integers for test case T)
Here, T is the number of test cases. For each test case, the first line contains an integer N indicating the number of elements, followed by a line with N space-separated integers.
outputFormat
For each test case, output the minimum cost on a separate line. The output is written to standard output (stdout).
## sample2
3
4 8 6
4
10 10 10 10
4
0
</p>