Best Position for a Service Centre
From LeetCode. Geometric median. Solve the geometry problem "Best Position for a Service Centre".
Examples
Input: [1,2,3]
Output: 0
Input: [2,3,4]
Output: 0
Hints
The geometric median minimizes Σ||p − pi|| (sum of Euclidean distances). Unlike the centroid (mean), there is no closed-form solution — use Weiszfeld's iterative algorithm: start from the centroid, then each step reweights points by 1 / distance to the current candidate.
Iterate until the candidate moves less than 1×10⁻⁷. On each step, compute the weighted average: new_x = Σ(xi / di) / Σ(1 / di), where di = max(ε, ||candidate − pi||) with ε ≈ 1×10⁻¹² to prevent division by zero when a point is exactly at the candidate.
If all points are identical, the geometric median is that point itself — return immediately. For collinear points, the geometric median lies on the line but is not necessarily the midpoint; Weiszfeld still converges correctly.
Best Position for a Service Centre
**From LeetCode.** Geometric median. Solve the geometry problem "Best Position for a Service Centre".