#K75147. Minimum Operations to Equal Array Elements

    ID: 34355 Type: Default 1000ms 256MiB

Minimum Operations to Equal Array Elements

Minimum Operations to Equal Array Elements

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

The optimal strategy is to convert every element to the median value of the array. Mathematically, if the array is sorted and the median is \(m\), then the minimum number of operations is:

[ \text{operations} = \sum_{i=1}^{n} |a_i - m| ]

For example, given the array [1, 2, 3, 4], the median is 3 and the minimum number of operations is calculated as \(|1-3| + |2-3| + |3-3| + |4-3| = 4\).

inputFormat

The input is given via standard input (stdin) and consists of two lines:

  • The first line contains a single integer n — the number of elements in the array.
  • The second line contains n space-separated integers representing the elements of the array.

outputFormat

Print a single integer on standard output (stdout), representing the minimum number of operations required to make all elements of the array equal.

## sample
4
1 2 3 4
4

</p>