#C1094. Minimum Cost to Equal Elements
Minimum Cost to Equal Elements
Minimum Cost to Equal Elements
You are given a list of n integers. Your task is to find the minimum cost required to make all the elements of the list equal. The cost is defined as the sum of absolute differences between each element and a chosen target value.
In mathematical terms, given a list \(a_1, a_2, \dots, a_n\), you need to find an integer \(t\) such that the value
[ \text{cost} = \sum_{i=1}^n |a_i - t| ]
is minimized. It can be shown that the optimal target value for \(t\) is the median of the list. Use this fact to compute the answer efficiently.
inputFormat
The input is read from stdin and contains two lines:
- The first line contains an integer \(n\) (\(1 \le n \le 10^5\)) representing the number of elements in the list.
- The second line contains \(n\) space-separated integers \(a_1, a_2, \dots, a_n\) representing the list elements.
outputFormat
Output a single integer to stdout: the minimum cost required to make all the elements equal.
## sample4
1 2 3 4
4
</p>