Trains the technique from
LeetCode 1478Allocate MailboxesThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A lane runs dead straight, and houses[i] is the position of one house along it, measured in metres from the lane's start. No two houses stand at the same position, and the positions arrive in no particular order.
The council will install exactly taps water taps, each at a whole-metre position on the lane. A tap may stand at the same position as a house, and two taps may stand at the same position. Every household then draws water from whichever tap is closest to its own house, walking the distance between the two positions.
Return the smallest total walking distance over all households that any placement of the taps can achieve.
Example 1
Put one tap at position 5 and the other at position 10000. The nine close households walk 4, 3, 2, 1, 0, 1, 2, 3 and 4 metres, and the far household walks nothing.
Example 2
Put one tap at position 2 and the other at position 9. The households at 1, 2 and 4 walk 1, 0 and 2 metres to the first tap, and the households at 7 and 9 walk 2 and 0 metres to the second.
Example 3
There are as many taps as houses, so a tap can stand at every house and nobody has to walk.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def least_total_walk(houses: list[int], taps: int) -> int:public int leastTotalWalk(int[] houses, int taps)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.