Minimize Sum of Distances to Warehouses
Learn this problemProblem statement
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
minSumDistancesToWarehouses(dist_centers: int[]) → int
Complete the function minSumDistancesToWarehouses in the editor.
minSumDistancesToWarehouses has the following parameter:
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
Examples
Example 1
dist_centers = [1, 6]return = 0Optimal 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.
Example 2
dist_centers = [1, 2, 5, 6]return = 2Optimal 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
⛈️More Amazon problems
- Secure Maximum DeliveriesOA · Seen Jul 2026
- Find Median from Data StreamONSITE INTERVIEW · Seen Jul 2026
- Handwritten SigmoidPHONE SCREEN · Seen Jul 2026
- Handwritten SoftmaxPHONE SCREEN · Seen Jul 2026
- Koko Eating BananasONSITE INTERVIEW · Seen Jul 2026
- Loyal Customers Across Two DaysONSITE INTERVIEW · Seen Jul 2026
- Maximum System Memory CapacityOA · Seen Jul 2026
- Package Delivery SystemOA · Seen Jul 2026