← ALL NOTES
Array

462. Minimum Moves to Equal Array Elements II

The target has to be the median, and the shortest way to see it is to stop thinking about a target at all. Pair the smallest element with the largest. Wherever those two meet, the pair costs at least max - min moves, and it costs exactly that whenever the meeting point lies between them. Peel the pair off, repeat on what is left, and you get a chain of nested intervals whose gaps sum to a lower bound no target can beat. One value sits inside every interval in the chain at once, so it hits every lower bound simultaneously: the median.

Loading…