#K76177. Minimum Moves to Equal Elements

    ID: 34585 Type: Default 1000ms 256MiB

Minimum Moves to Equal Elements

Minimum Moves to Equal Elements

You are given a sequence of n integers. Your task is to determine the minimum number of moves required to make all the elements in the sequence equal. In one move, you can increment or decrement any element by 1.

The solution is based on the fact that choosing the median of the sequence minimizes the total number of moves. In other words, if the sorted array is \(a_1, a_2, \dots, a_n\) and \(m = a_{\lceil n/2 \rceil}\), the answer is:

\(\sum_{i=1}^{n} |a_i - m|\)

inputFormat

The input is read from standard input and consists of two lines:

  1. The first line contains a single integer n (1 ≤ n ≤ 105), representing the number of elements in the sequence.
  2. The second line contains n space-separated integers, representing the elements of the sequence. Each element can be a positive, zero, or negative integer.

outputFormat

Output a single integer to the standard output — the minimum number of moves required to make all the sequence elements equal.

## sample
4
1 2 3 4
4