Pick the median
transcript
Warehouses hold different stock. A move changes one by one unit. Make them all equal, in the fewest moves. The stock can reach a billion units each. Ten units, or a billion, it is the same problem.
Here is the stock, sorted. Pair the smallest with the largest. Any target between them costs sixteen. The target can sit anywhere between them.
The middle value lies between every such pair. So one target serves all the pairs. Here that is fifteen, for sixteen moves. This is the median of the sorted list.
A common slip is to use the mean. The mean is eleven, and costs twenty moves. The median is fifteen, and costs only sixteen. A stress test on small lists finds the slip at once.
Sort the list first. The middle position holds the median only when sorted. Then take the middle position. An unsorted middle position gives the wrong target.
The median beats the mean. A stress test shows it. Full breakdown in the lecture.