#K77662. Collecting Gems with Minimal Distance
Collecting Gems with Minimal Distance
Collecting Gems with Minimal Distance
In this problem, you are given n gem coordinates on a one-dimensional line. Starting at the origin (0), your task is to collect all the gems and return to the starting point. The gems can be collected in any order, but the optimal strategy is to sort the gem coordinates in non-decreasing order and then travel from 0 to the smallest gem, then from gem to gem until reaching the largest one, and finally return to the origin.
The minimal total distance D can be formulated as follows:
\[
D = |x_1 - 0| + \sum_{i=2}^{n} |x_i - x_{i-1}| + |x_n - 0|,
\]
where \(x_1 \le x_2 \le \dots \le x_n\) are the gem coordinates after sorting. All input coordinates are integers and for the purpose of this problem, you can assume they are non-negative.
inputFormat
The first line of the input contains a single integer n denoting the number of gems.
The second line contains n space-separated integers, each representing the coordinate of a gem.
Note: All coordinates are guaranteed to be integers and non-negative.
outputFormat
Output a single integer indicating the minimal distance Martha needs to travel to collect all the gems and return to the starting point.
## sample4
1 3 6 2
12