#K14116. Minimum Operations to Equalize Array Elements

    ID: 24064 Type: Default 1000ms 256MiB

Minimum Operations to Equalize Array Elements

Minimum Operations to Equalize Array Elements

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

The optimal strategy is to make all elements equal to the median of the array. Mathematically, if the array elements are a1, a2, ..., an and the median is m, the minimum number of operations required is given by

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

Note that if there are multiple medians (in an even-length array), choosing any one of them will yield the minimum total cost.

inputFormat

The input is given via stdin and has the following format:

  1. The first line contains a single integer n (1 ≤ n ≤ 105), the number of elements in the array.
  2. The second line contains n space-separated integers, where each integer ai satisfies -109 ≤ ai ≤ 109.

outputFormat

Output a single integer to stdout – the minimum number of operations required to equalize the array.

## sample
3
1 2 3
2