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:
Optimal grouping: [1,4] with mailbox at position 2.5, [8,10] with mailbox at position 9, [20] with mailbox at position 20. Total distances: (1.5+1.5) + (1+1) + 0 = 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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code