D - Khalid and Sticks

Description:

Khaled has \(n\) sticks with integer positive lengths \(a_1, a_2, \dots, a_n\).

For every stick, Khaled can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from \(a\) to \(n\) is \(|a-b|\), where \(|x|\) means the absolute value of \(x\).

Khaled wants to change the lengths of some sticks (possibly all or none), such that all sticks' lengths are equal, with minimum cost.

Can you help Khaled determine the minimum cost to make all sticks have the same length?

Program Input:

The first line contains single integer \(n\) , the number of sticks.

The second line contains \(n\) integers \(a_i\) , the length of the sticks.

Constraints:

\(1 \leq n \leq 1000\)

\(1 \leq a_i \leq 100\)

Program Output:

A single line that contains the minimum cost to make all sticks have the same length.

Sample Testcase 0:

Input:

3

10 1 4

Output:

9

Explanation:

You can change the sticks to length 4 with cost \(|10 – 4| + |1 – 4| + |4 – 4| = 6 + 3 + 0 = 9\)

Sample Testcase 1:

Input:

5

1 1 2 2 3

Output:

3

Explanation:

You can change the sticks to length 2 with cost \(|1 – 2| + |1 – 2| + |2 – 2| + |2 – 2| + |3 – 2| = 1 + 1 + 0 + 0 + 1 = 3\)


CodeBox

Information

Author(s) Muhannad Alwarawreh
Deadline No deadline
Submission limit No limitation

Sign in