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] 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.
To solve this, we will follow these steps −
sort the list houses
Define a function util() . This will take idx, n, k
if k is same as 1, then
core := houses[quotient of (n + idx)/2]
return sum of all elements of [|houses[i] - core| for each i in range idx to n])
result := infinity
for i in range idx to n, do
if n - i < k - 1, then
come out from the loop
result := minimum of result and util(idx, i, 1) + util(i+1, n, k - 1)
return result
From the main method do the following:
return util(0, size of houses - 1, k)
Example
Let us see the following implementation to get better understanding
def solve(houses, k): houses.sort() def util(idx, n, k): if k == 1: 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): if n - i < k - 1: break result = min(result, util(idx, i, 1) + util(i+1, n, k - 1)) return result return util(0, len(houses) - 1, k) houses = [6,7,9,16,22] k = 2 print(solve(houses, k))
Input
[6,7,9,16,22], 2
Output
9