Problem · Array

Compute Minimum Total Distance

Learn this problem
MediumAmazon logoAmazonFULLTIMEOA
See Amazon hiring insights

Problem statement

FastPrep.io has recently expanded its operations by establishing n distribution centers in a newly developed location in Cal. To efficiently manage the supply chain, they plan to set up two warehouses that will serve these distribution centers.

It is important to note that both the distribution centers and warehouses are positioned along a straight line. Each distribution center will have its demands fulfilled by the nearest warehouse.

A dedicated logistics team is tasked with determining the optimal locations for these two warehouses. Their primary objective is to minimize the total sum of distances between each distribution center and its closest warehouse, ensuring the most efficient and cost-effective supply chain operations.

Please complete function computeMinimumTotalDistance in the editor. This function has a parameter called distribution_center_locations, which is an integer array representing the positions of the distribution centers along the straight line. The function should return the minimum total distance between the distribution centers and the warehouses closest to them.

🦉Supa grateful for having a reliable helper like 🌷spike🌷 around 😊

Function

computeMinimumTotalDistance(distribution_center_locations: int[]) → int

Examples

Example 1

distribution_center_locations = [1, 2, 3]return = 1
Example 1 illustration
One optimal solution is to position the 2 warehouses at x1 = 1 and x2 = 2. The minimum sum of the distances between distribution centers and the warehouses closest to them is 0 + 0 + 1 = 1.

Example 2

distribution_center_locations = [1, 6]return = 0
Place one warehouse at x1 = 1 and the other at x2 = 6. Each center is 0 distance from its nearest warehouse.

Example 3

distribution_center_locations = [1, 2, 5, 6]return = 2
One optimal solution is to place the warehouses at x1 = 1 and x2 = 6. Distances to the nearest warehouse for centers at [1, 2, 5, 6] are [0, 1, 1, 0], giving a total of 2.

Constraints

  • 2 <= n <= 2 * 103
  • 0 <= distribution_center_locations[i] <= 106

More Amazon problems

drafts saved locally
public int computeMinimumTotalDistance(int[] distribution_center_locations) {
  // write your code here
}
distribution_center_locations[1, 2, 3]
expected1
checking account