#K84722. Minimum Operations to Equalize Array

    ID: 36483 Type: Default 1000ms 256MiB

Minimum Operations to Equalize Array

Minimum Operations to Equalize Array

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 to make all the elements equal.

A well-known approach to solving this problem is to choose a target value and compute the sum of absolute differences between each element and the target. It can be proven that the optimal target is the median of the array. In the case when n is even, any value between the two middle values minimizes the sum; one common choice is to pick the element at position \( \lfloor n/2 \rfloor \) (0-indexed).

Hint: If the sorted array is \(a_1, a_2, \dots, a_n\), then the median is given by:

[ \text{median} = \begin{cases} a_{\frac{n+1}{2}}, & \text{if } n \text{ is odd}\ a_{\frac{n}{2}} \quad (\text{or any number between } a_{\frac{n}{2}} \text{ and } a_{\frac{n}{2}+1}), & \text{if } n \text{ is even} \end{cases} ]

Once the median is determined, the answer is the sum over all elements: \( \sum_{i=1}^{n} |a_i - \text{median}| \).

inputFormat

Input is read from standard input. The first line contains a single integer n representing the number of elements in the array. The second line contains n space-separated integers representing the elements of the array.

outputFormat

Output to standard output a single integer, representing the minimum number of operations required to make all the array elements equal.

## sample
5
1 2 3 4 5
6

</p>