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
Allocate Mailboxes - Optimal Solution INPUT Street (number line) 1 4 8 10 20 = House houses = [1, 4, 8, 10, 20] k = 3 (mailboxes) 5 houses, 3 mailboxes Minimize total distance from houses to mailboxes ALGORITHM STEPS 1 Precompute Cost cost[i][j] = min dist for houses[i..j] with 1 mailbox 2 Median Property Best mailbox position = median of house locations 3 DP Transition dp[i][j] = min cost for first i houses, j mailboxes 4 Optimal Grouping Group: [1,4], [8,10], [20] Mailboxes at: 4, 8, 20 DP Formula: dp[i][j] = min over m: dp[m][j-1] + cost[m+1][i] Time: O(n^2 * k), Space: O(n*k) FINAL RESULT M1@4 M2@8 M3@20 Distance Breakdown: House 1 --> M1(4): |1-4| = 3 House 4 --> M1(4): |4-4| = 0 House 8 --> M2(8): |8-8| = 0 House 10 --> M2(8): |10-8| = 2 House 20 --> M3(20): |20-20| = 0 Output: 5 Total: 3+0+0+2+0 = 5 [OK] Minimum achieved! Key Insight: For a group of houses served by one mailbox, the optimal position is the MEDIAN house location. This minimizes total distance. Use DP to find the best way to partition n houses into k groups, where each group gets one mailbox at its median position. TutorialsPoint - Allocate Mailboxes | Optimal DP Solution
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