All problems

Problem 471

Minimum Moves to Equal Array Elements

Medium · 20 pts · Array, Math, Sorting

Problem

In one move you may increase or decrease a single element of the array by 1. Find the minimum number of moves needed to make all elements equal. The best common value is the median of the array: moving towards the median from both sides always reduces the total distance. The answer can exceed 32 bits, so use a 64-bit integer.

Input

First line: N. Second line: N integers.

Output

Print the minimum number of moves.

Constraints

1 <= N <= 100000; -1000000000 <= A[i] <= 1000000000

Example input

3
1 2 3

Example output

2

Explanation

For 1 2 3, moving every element to the median 2 takes 1 + 0 + 1 = 2 moves.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Queue Reconstruction by Height Next: Wiggle Subsequence