#K63882. Minimum Operations to Equalize Array Elements
Minimum Operations to Equalize Array Elements
Minimum Operations to Equalize Array Elements
You are given an array of N integers. In one operation, you can increment or decrement any element by 1. Your task is to determine the minimum number of operations required such that all elements of the array become equal.
It can be shown that choosing the median of the array minimizes the sum of absolute differences. In mathematical terms, given an array \(a_1, a_2, \dots, a_N\), if \(m\) is the median of the array, then the minimum number of operations is:
[ \text{operations} = \sum_{i=1}^{N} |a_i - m| ]
Note: In the case of an even number of elements, any number between the two middle values is an optimal target; here, for simplicity, we choose the \(\lceil N/2 \rceil\)-th element after sorting the array.
inputFormat
The first line contains an integer N, the number of elements in the array.
The second line contains N space-separated integers representing the elements of the array.
outputFormat
Output a single integer, the minimum number of operations required to make all array elements equal.
## sample5
1 2 3 4 5
6
</p>