#1478
Allocate Mailboxes
HardArrayMathDynamic ProgrammingSortingDynamic ProgrammingGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n² * C(n, k)) | O(n² * k) |
| Space | O(1) | O(n * k) |
💡
Intuition
Time O(n² * k)Space O(n * k)
The optimal solution uses dynamic programming to efficiently compute the minimum distance by breaking the problem into smaller subproblems. It builds on the idea that the best position for a mailbox is often near the median of the houses.
⚙️
Algorithm
4 steps- 1Step 1: Sort the houses array.
- 2Step 2: Create a DP table where dp[i][j] represents the minimum distance for the first i houses with j mailboxes.
- 3Step 3: For each house, calculate the minimum distance for all possible mailbox positions and update the DP table.
- 4Step 4: Return dp[n][k] where n is the number of houses.
solution.py20 lines
1# Full working Python code
2import sys
3
4def minDistance(houses, k):
5 houses.sort()
6 n = len(houses)
7 dp = [[0] * (k + 1) for _ in range(n + 1)]
8 for i in range(1, n + 1):
9 for j in range(1, k + 1):
10 dp[i][j] = sys.maxsize
11 for p in range(i):
12 distance = calculateDistance(houses, p, i - 1)
13 dp[i][j] = min(dp[i][j], dp[p][j - 1] + distance)
14 return dp[n][k]
15
16
17def calculateDistance(houses, left, right):
18 mid = (left + right) // 2
19 median = houses[mid]
20 return sum(abs(house - median) for house in houses[left:right + 1])ℹ
Complexity note: The time complexity is significantly improved because we avoid checking all combinations directly and instead use dynamic programming to build solutions incrementally.
- 1The optimal mailbox positions often align with the median of the houses.
- 2Dynamic programming allows us to break down the problem into manageable pieces, reducing the need for exhaustive combinations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.