- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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)

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))

[6,7,9,16,22], 2

9

- Related Questions & Answers
- Program to find the minimum edit distance between two strings in C++
- Program to find minimum distance to the target element using Python
- Program to find maximum distance between empty and occupied seats in Python
- Find the minimum distance between two numbers in C++
- Program to find minimum total cost for equalizing list elements in Python
- Program to find distance of shortest bridge between islands in Python
- Total Distance to Visit City Blocks in Python
- Program to find minimum distance of two given words in a text in Python
- Find maximum distance between any city and station in Python
- Program to find list showing total distance required to move all balls to current position in Python
- Program to find maximum distance between a pair of values in Python
- Find maximum difference between nearest left and right smaller elements in Python
- Total Hamming Distance in C++
- Program to find minimum distance that needs to be covered to meet all person in Python
- Distance to nearest vowel in a string - JavaScript

Advertisements