Sub topic 14
Minimising Sums of Absolute Values with the Median
This chapter assumes you can read |x − a| as the distance from x to a, and that you can split a modulus expression at its critical points (covered in the chapter on multiple modulus terms). Here we look at one question CAT asks often: which x makes a sum like |x − a₁| + |x − a₂| + … + |x − aₙ| as small as possible?
The result
Sort the points a₁ ≤ a₂ ≤ … ≤ aₙ. The sum of distances is smallest when x is at the median of the points.
| Number of points | Where the minimum occurs |
|---|---|
| Odd (n = 2k + 1) | Exactly at the middle point a_(k+1) |
| Even (n = 2k) | Anywhere in the closed interval [a_k, a_(k+1)] |
Why the median works
f(x) = Σ|x − aᵢ| is piecewise linear. Between two critical points, each term |x − aᵢ| has slope +1 if aᵢ lies to the left of x and −1 if aᵢ lies to the right. So:
slope of f = (points to the left of x) − (points to the right of x)
When x is to the left of the median, more points lie on its right, so the slope is negative and f is falling. When x is to the right of the median, the slope is positive and f is rising. With an even count, the slope is exactly 0 between the two middle points, so f is flat there.
The same result follows from pairing. Pair the outermost points, then the next pair in, and so on. For any pair a ≤ b, |x − a| + |x − b| ≥ b − a, with equality exactly when x is in [a, b]. The median lies inside every pair's interval at once, so it meets every lower bound together.
Worked examples
For an odd count, take f(x) = |x − 1| + |x − 3| + |x − 8|. The median is 3, so the minimum is 2 + 0 + 5 = 7.
For an even count, take f(x) = |x − 1| + |x − 4| + |x − 7| + |x − 10|. The pairs are (1, 10) and (4, 7). The minimum is (10 − 1) + (7 − 4) = 12, and f reaches it at every x in [4, 7].
points = [1, 4, 7, 10]
best = min(sum(abs(x - a) for a in points) for x in range(-20, 21))
print(best) # 12, reached for any x between 4 and 7Common errors
- Coefficients count as repeated points. In |x − 1| + 2|x − 5|, the term 2|x − 5| is two copies of the point 5. The points are 1, 5, 5, so the median is 5 and the minimum is 4.
- Rewrite terms in the form |x − a| first. For example, |2x − 6| = 2|x − 3|, which is the point 3 counted twice.
- Read what the question asks for. In the even case, a question about how many integer values of x give the minimum is asking you to count the integers in [ak, a(k+1)]. Count both endpoints.
Exercise
Find the minimum value of |x − 2| + |x − 5| + |x − 9| + |x − 12| + |x − 20|.
Show answer
There are 5 points, so the median is 9. The minimum is 7 + 4 + 0 + 3 + 11 = 25.
Exercise
For f(x) = |x + 3| + |x − 1| + |x − 6| + |x − 10|, find the minimum value and the number of integers x at which f reaches it.
Show answer
The pairs are (−3, 10) and (1, 6), so the minimum is 13 + 5 = 18. f reaches it for every x in [1, 6], which contains 6 integers.