#K91767. Minimal Operations to Equalize Array Elements

    ID: 38049 Type: Default 1000ms 256MiB

Minimal Operations to Equalize Array Elements

Minimal Operations to Equalize Array Elements

You are given an array of integers. Your task is to determine the minimum number of operations required to make all elements equal. In each operation, you can increment or decrement an element by 1.

The optimal strategy is to equalize all elements to the median of the array. If the array contains an even number of elements, you should choose the left-middle element as the median, i.e., \(a_{\frac{n}{2}}\) when the array is sorted (1-indexed) or more precisely \(\text{median} = arr\left[\frac{n}{2}-1\right]\) (0-indexed).

Input Format: The first line contains an integer \(n\) denoting the number of elements. The second line contains \(n\) space-separated integers.

Output Format: Output a single integer denoting the minimum number of operations required to equalize all elements.

inputFormat

The first line of input contains a single integer \(n\) (\(1 \le n \le 10^5\)), representing the number of elements in the array.

The second line contains \(n\) space-separated integers \(a_1, a_2, \dots, a_n\) where each \(a_i\) satisfies \(|a_i| \le 10^9\).

outputFormat

Output a single integer: the minimum number of operations required to make all elements equal.

## sample
5
1 2 3 4 5
6