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
Allocate Mailboxes: Minimize Total Walking Distance1481020HouseHouseHouseHouseHouseM1M2M3MailboxMailboxMailboxOptimal placement: Houses [1,4] → M1, House [8] → M2, Houses [10,20] → M3Total walking distance: 2 + 0 + 3 = 5🎯 Key Insight: Use DP to try all ways to partition houses optimally
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
Asked in
Google 12 Facebook 8 Amazon 6
28.5K Views
Medium Frequency
~45 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen