#K47282. Minimum Operations to Equalize Array Elements
Minimum Operations to Equalize Array Elements
Minimum Operations to Equalize Array Elements
You are given an integer n and an array a of n integers. In one operation, you can increase or decrease any element by 1. The goal is to make all elements equal while minimizing the total number of operations.
The optimal strategy is to adjust all elements to the median of the array. In fact, if we denote the median by \(m\), the total number of operations required is given by
\[ \text{Operations} = \sum_{i=1}^{n} |a_i - m| \]Note that when \(n\) is even, any value between the two middle numbers minimizes the sum; for simplicity, we choose the upper median.
inputFormat
The input is given from stdin and consists of two lines. The first line contains a single integer n denoting the number of elements in the array. The second line contains n space-separated integers representing the elements of the array.
Example:
5 1 2 3 4 5
outputFormat
Output to stdout a single integer which is the minimum number of operations required to make all array elements equal.
## sample5
1 2 3 4 5
6