FastPrepFastPrep
Problem Brief

Minimize Sum of Distances to Warehouses

FULLTIMEOA
See Amazon online assessment and hiring insights

Amazon has recently established n distribution centers in a new location. They want to set up 2 warehouses to serve these distribution centers. Note that the centers and warehouses are all built along a straight line. A distribution center has its demands met by the warehouse that is closest to it. A logistics team wants to choose the location of the warehouses such that the sum of the distances of the distribution centers to their closest warehouses is minimized.

Given an array dist_centers, that represent the positions of the distribution centers, return the minimum sum of distances to their closest warehouses if the warehouses are positioned optimally.

Function Description

Complete the function minSumDistancesToWarehouses in the editor.

minSumDistancesToWarehouses has the following parameter:

  1. int[] dist_centers: an array of integers representing the positions of the distribution centers

Returns

int: the minimum sum of distances to their closest warehouses

1Example 1

Input
dist_centers = [1, 6]
Output
0
Explanation

Optimal solution: Place one warehouse at x1 = 1 and the other at x2 = 6. The sum of distances to the nearest warehouse is 0 + 0 = 0.

2Example 2

Input
dist_centers = [1, 2, 5, 6]
Output
2
Explanation

Optimal solution: Place one warehouse at x1 = 1 and the other at x2 = 6. The distances to the nearest warehouse are [0, 0, 1, 0], resulting in a total distance sum of 2.

Constraints

Limits and guarantees your solution can rely on.

⛈️
public int minSumDistancesToWarehouses(int[] dist_centers) {
  // write your code here
}
Input

dist_centers

[1, 6]

Output

0

Sign in to submit your solution.