#C8528. Minimum Steps to Equalize Array Elements
Minimum Steps to Equalize Array Elements
Minimum Steps to Equalize Array Elements
You are given t test cases. In each test case, you are provided with an integer n and an array of n integers. Your task is to determine the minimum number of steps required to make all the array elements equal. In one step, you can increment or decrement an element by 1.
The optimal strategy is to make all elements equal to the median of the array. This is because the sum of absolute differences is minimized when the target value is the median. Formally, if the sorted array is \(a_1, a_2, \dots, a_n\), and the median is \(m = a_{\lfloor n/2 \rfloor + 1}\) (using 0-indexed notation, it is at index \(\lfloor n/2 \rfloor\)), then the minimum number of steps is given by:
[ \text{steps} = \sum_{i=1}^{n} |a_i - m| ]
Implement a solution that reads the input from stdin and outputs the result for each test case on a new line.
inputFormat
The first line contains a single integer t representing the number of test cases. Then for each test case:
- The first line contains an integer n, the size of the array.
- The second line contains n space-separated integers.
outputFormat
For each test case, output a single integer — the minimum number of steps required to make all elements equal. Print each result on a new line.
## sample5
3
1 2 3
4
1 1 1 1
5
1 3 2 5 4
3
10 10 10
2
1 100
2
0
6
0
99
</p>