#K746. Minimum Operations to Equal Elements
Minimum Operations to Equal Elements
Minimum Operations to Equal Elements
You are given t test cases. In each test case, you are provided 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 increase or decrease an element by 1.
It can be proven that the optimal solution is to make every element equal to the median of the array. Mathematically, if the array is \(A = [a_1, a_2, \dots, a_n]\), you want to minimize the quantity:
[ \min_{k \in \mathbb{Z}} \sum_{i=1}^{n} |a_i - k| ]
Note that for arrays with an even number of elements, choosing either of the two middle values yields an optimal solution.
inputFormat
The first line of input 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 elements of the array.
outputFormat
For each test case, output a single line containing the minimum number of operations required to make all the array elements equal.
## sample1
5
1 2 3 4 5
6
</p>