Given positions of several points on a line, find the best meeting point that minimizes the total travel distance.
Reconnaissance
gfgYou are given the positions of several friends on a straight line. You want to choose a meeting point on that same line so that the sum of distances from all friends to that point is as small as possible.
Your task is to compute this minimum possible total distance.
For points on a line, the best meeting point is at a median position. This problem asks you to evaluate the minimum total travel distance for the given set of positions.
Example 1
Input
5 1 2 3 4 5
Output
6
Explanation
Choosing meeting point 3 gives distances 2 + 1 + 0 + 1 + 2 = 6.
Example 2
Input
4 -1 2 6 7
Output
12
Explanation
Any point between 2 and 6 is optimal. One valid choice is 2, giving 0 + 0 + 4 + 5 = 9; however, for integer meeting points the minimum is achieved at 6 as well with 3 + 4 + 0 + 1 = 8. The true minimum over all real points is 9. This illustrates why the median interval matters.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.