#K51922. Minimum Moves to Equal Array Elements

    ID: 29195 Type: Default 1000ms 256MiB

Minimum Moves to Equal Array Elements

Minimum Moves to Equal Array Elements

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

The optimal strategy is to bring all elements to the median of the array. Mathematically, the number of moves required is given by:

$$ \text{moves} = \sum_{i=1}^{n} |\text{nums}_i - \text{median}| $$

where \(n\) is the number of elements in the array and \(\text{median}\) is the middle element after sorting the array.

inputFormat

The input is read from standard input (stdin) in the following format:

  • The first line contains an 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 a single integer on standard output (stdout) representing the minimum number of moves required to make all array elements equal.

## sample
3
1 2 3
2