All problems

Problem 815

Minimum Moves to Equal Array Elements II

Medium · 20 pts · Array, Math, Sorting

Problem

In one move you may increase or decrease any single element by 1. Find the minimum number of moves needed to make all elements equal. If all elements end at the value T, the cost is the sum of |A[i] - T|, and this sum is smallest when T is a median of the array (the middle element after sorting). The answer can exceed 2^31, so use a 64-bit integer.

Input

The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1].

Output

Print the minimum number of moves.

Constraints

1 <= N <= 100000; -10^9 <= A[i] <= 10^9

Example input

3
1 2 3

Example output

2

Explanation

For 1 2 3, moving everything to the median 2 costs 1 + 0 + 1 = 2 moves, which is the minimum.

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

Previous: Maximum Product of Three Numbers Next: Number of Good Pairs