Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find minimum total distance between house and nearest mailbox in Python
Suppose we have an array called houses and have another value k. Here houses[i] represents the location of the ith house along a street, we have to allocate k mailboxes in the street, and find the minimum total distance between each house and its nearest mailbox.
So, if the input is like houses = [6,7,9,16,22] and k = 2, then the output will be 9 because if we place mailbox at 7 and 18, then minimum total distance from each house is |6-7|+|7-7|+|9-7|+|16-18|+|22-18| = 1+0+2+2+4 = 9.
Algorithm
To solve this problem, we use a recursive approach with dynamic programming:
Sort the houses array
For k=1, place the mailbox at the median position to minimize total distance
For k>1, try all possible positions for the first mailbox and recursively solve for remaining houses
Example
def solve(houses, k):
houses.sort()
def util(idx, n, k):
# Base case: only one mailbox left
if k == 1:
# Place mailbox at median position
core = houses[(n + idx) // 2]
return sum([abs(houses[i] - core) for i in range(idx, n + 1)])
result = float('inf')
for i in range(idx, n + 1):
# Not enough houses left for remaining mailboxes
if n - i < k - 1:
break
# Try placing first mailbox covering houses[idx:i+1]
# Then solve for remaining houses with k-1 mailboxes
result = min(result, util(idx, i, 1) + util(i+1, n, k - 1))
return result
return util(0, len(houses) - 1, k)
# Test the solution
houses = [6, 7, 9, 16, 22]
k = 2
result = solve(houses, k)
print(f"Houses: {houses}")
print(f"Number of mailboxes: {k}")
print(f"Minimum total distance: {result}")
Houses: [6, 7, 9, 16, 22] Number of mailboxes: 2 Minimum total distance: 9
How It Works
The algorithm works by:
Sorting: Houses are sorted to work with consecutive segments
Median placement: For a single mailbox, placing it at the median minimizes total distance
Recursive partitioning: For multiple mailboxes, we try all ways to assign houses to the first mailbox, then solve recursively for the rest
Another Example
# Test with different input
houses = [1, 4, 8, 10, 20]
k = 3
result = solve(houses, k)
print(f"Houses: {houses}")
print(f"Number of mailboxes: {k}")
print(f"Minimum total distance: {result}")
Houses: [1, 4, 8, 10, 20] Number of mailboxes: 3 Minimum total distance: 5
Conclusion
This recursive solution with optimal mailbox placement finds the minimum total distance by trying all possible ways to partition houses among k mailboxes. The key insight is placing each mailbox at the median of its assigned houses to minimize distance.
