Allocate Mailboxes - Problem
Given an array houses where houses[i] is the location of the ith 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.
Input & Output
Example 1 — Basic Case
$
Input:
houses = [1,4,8,10,20], k = 3
›
Output:
5
💡 Note:
Allocate mailboxes at positions 1, 8, and 20. Houses [1,4] use mailbox at 1 (distance 0+3=3), house [8] uses mailbox at 8 (distance 0), houses [10,20] use mailbox at 20 (distance 10+0=10). But optimal is mailboxes at 3, 8, 15 giving total distance 5.
Example 2 — Two Mailboxes
$
Input:
houses = [2,3,5,12,18], k = 2
›
Output:
9
💡 Note:
Place first mailbox at position 3 for houses [2,3,5] (distances 1+0+2=3) and second mailbox at position 15 for houses [12,18] (distances 3+3=6). Total: 3+6=9.
Example 3 — One Mailbox
$
Input:
houses = [7,4,6,1], k = 1
›
Output:
8
💡 Note:
With only one mailbox, place it at median position. Sorted houses: [1,4,6,7]. Median between positions 1 and 2 is around 5. Place mailbox at 4 or 6. At position 5: distances are 4+1+1+2=8.
Constraints
- 1 ≤ k ≤ houses.length ≤ 100
- 1 ≤ houses[i] ≤ 104
- All the positions of houses are unique.
Visualization
Tap to expand
Understanding the Visualization
1
Input
Houses at positions [1,4,8,10,20] and k=3 mailboxes
2
Process
Find optimal mailbox positions using DP
3
Output
Minimum total distance is 5
Key Takeaway
🎯 Key Insight: For any group of houses, place the mailbox at the median position to minimize total distance
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code