FastPrepAllocate Mailboxes

Allocate Mailboxes

Bloomberg LP logoBloomberg LP● HardNEW GRADONSITE INTERVIEW
Learn

Problem statement

Houses stand at the integer positions in houses along one street. Install exactly k mailboxes at integer positions so that the sum of every house's distance to its nearest mailbox is as small as possible.

Return that minimum total distance.

Function

minMailboxDistance(houses: int[], k: int) → int

Examples

Example 1

houses = [5,10,15,20]k = 3return = 5

Mailboxes at 5, 10, and any median position between 15 and 20 give total distance 5.

Example 2

houses = [6,7,8,12]k = 2return = 2

Positions 7 and 12 serve the houses with total distance 2.

Constraints

  • 1 <= houses.length <= 100.
  • 1 <= k <= houses.length.
  • House positions are distinct integers between 1 and 10000.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int minMailboxDistance(int[] houses, int k) {
  // Write your code here.
}
houses[5,10,15,20]
k3
expected5
Checking account…