#C10677. Minimum Operations to Equalize Array
Minimum Operations to Equalize Array
Minimum Operations to Equalize Array
You are given T test cases. For each test case, you are given an integer n and an array of n integers. Your task is to determine the minimum number of operations required to make all elements of the array equal. In one operation, you can increment or decrement an element by 1.
It can be shown that the optimal strategy is to equalize all elements to the median of the array. In particular, if m is the median, the cost is given by:
\(\sum_{i=1}^{n} |a_i - m|\)
Please note that the median for an even number of elements is defined as the element at the \(\lfloor n/2 \rfloor\)-th position after sorting (0-indexed order using this convention minimizes the sum of absolute differences in this problem).
inputFormat
The first line contains an integer T — the number of test cases.
For each test case, the first line contains an integer n — the size of the array.
The second line contains n space-separated integers representing the array elements.
outputFormat
For each test case, print a single line containing the minimum number of operations needed to make all the array elements equal.
## sample4
3
1 2 3
2
2 4
5
5 5 5 5 5
4
1 2 2 1
2
2
0
2
</p>