Allocate Mailboxes Problem
Description
LeetCode Problem 1478.
Given the array houses where houses[i] is the location of the i^th house along a street and an integer k, allocate k mailboxes in the street.
Return the minimum total distance between each house and its nearest mailbox.
The test cases are generated so that the answer fits in a 32-bit integer.
Example 1:

Input: houses = [1,4,8,10,20], k = 3
Output: 5
Explanation: Allocate mailboxes in position 3, 9 and 20.
Minimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5
Example 2:

Input: houses = [2,3,5,12,18], k = 2
Output: 9
Explanation: Allocate mailboxes in position 3 and 14.
Minimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.
Constraints:
1 <= k <= houses.length <= 1001 <= houses[i] <= 10^4- All the integers of
housesare unique.
Solution
Approach: Interval DP with Median Costs
Sort the houses first. In an optimal answer, each mailbox serves a contiguous block of houses (the ones closest to it), so the problem becomes: split the sorted houses into k blocks and put one mailbox in each.
One mailbox for one block. For houses houses[i..j], the best place for a single mailbox is the median, which minimizes the sum of absolute distances. We do not even need the median explicitly. Let cost[i][j] be that minimum total distance. The outermost pair houses[i] and houses[j] together contribute houses[j] - houses[i] wherever the mailbox sits between them, so:
cost[i][j] = cost[i + 1][j - 1] + houses[j] - houses[i], withcost[i][i] = 0.
Filling i from right to left builds the whole table in O(n2).
Splitting into k blocks. Let f[i][j] be the minimum total distance for the first houses houses[0..i] using j mailboxes. With one mailbox, f[i][1] = cost[0][i]. Otherwise, let the last mailbox serve houses[p + 1..i]:
f[i][j] = min over p of f[p][j - 1] + cost[p + 1][i].
p must leave at least j - 1 houses for the other mailboxes, so p >= j - 2. The answer is f[n - 1][k]. Using more mailboxes than houses never helps, which is why j stops at i + 1.
Complexity: O(n2 * k) time and O(n2) extra space, where n is the number of houses.
class Solution:
def minDistance(self, houses: List[int], k: int) -> int:
houses.sort()
n = len(houses)
# cost[i][j]: one mailbox (at the median) serving houses[i..j]
cost = [[0] * n for _ in range(n)]
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
cost[i][j] = cost[i + 1][j - 1] + houses[j] - houses[i]
INF = float("inf")
# f[i][j]: houses[0..i] served by j mailboxes
f = [[INF] * (k + 1) for _ in range(n)]
for i in range(n):
f[i][1] = cost[0][i]
for j in range(2, min(k, i + 1) + 1):
for p in range(j - 2, i): # the last mailbox serves houses[p+1..i]
f[i][j] = min(f[i][j], f[p][j - 1] + cost[p + 1][i])
return f[n - 1][k]