840. Post Box Placement

A courier company plans to set up k parcel lockers along a straight road. The positions of the customer homes are given in houses (unsorted, repeats allowed), and every locker must be placed exactly at the position of some home. Each customer walks to the closest locker.

Return the minimum possible total walking distance summed over all homes. If k is at least the number of homes, every home can host its own locker and the answer is 0. The input array must not be modified.

Aim for roughly time O(k * n log n) after sorting, using the monotone-split property of the optimal blocks, and space O(n).

Example 1

Input:
houses = [2,5,6,12,13,30], k = 2
Output:
18
Explanation:

Boxes at 6 and 30 give walking distances 4, 1, 0, 6, 7 and 0, a total of 18, and no other pair of houses does better.

Example 2

Input:
houses = [40,10,25,70,55], k = 3
Output:
30
Explanation:

Boxes at 10, 25 and 55 leave only the houses at 40 and 70 walking 15 each, so the total is 30.

Constraints

1 ≤ houses.length ≤ 104

0 ≤ houses[i] ≤ 105

1 ≤ k ≤ 100

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(k * n log n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…