Unify Numbers

3.5

543 votes
Implementation, Sorting, Approved, Easy-Medium
Problem

Today Omar has assignment problems from his math professor. Yes, Omar has infinite number of questions that he must solve today. The first problem went something like this.

Given N integers in the form of Ai where 1iN, Omar wants to make each number Ai in the N numbers equal to M. To convert a number Ai to M, it will cost |MAi| units. The problem asks to find out the minimum cost to convert all the N numbers to M, so you should choose the best M to get the minimum cost.

Omar gets bored easily from these kind of questions, can you solve it for him ?

Input:

First line of the input contains an integer T denoting the number of test cases.
First line of every test-case contains an integer N.
Second line of every test case contains N space separated integers Ai.

Output:

For each case, print the minimum cost that Omar needs to pay to convert each Ai to M, in a separate line.

Constraints:

  • 1T10.
  • 1N105.
  • 1Ai109

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

One of the best Ms you could choose in this case is 3.
So the answer = |13|+|23|+|43|+|53|=6.

Editor Image

?