Description
Solutions
Compute Minimum Total Distance
🔥 FULLTIME

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 😊

Example 1:

Input:  distribution_center_locations = [1, 2, 3]
Output: 1
Explanation:
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:

Input:  distribution_center_locations = [1, 6]
Output: 0
Explanation:
Place one warehouse at x1 = 1 and the other at x2 = 6. Each center is 0 distance from its nearest warehouse. (Updated on 02-05-2025, credit to spike :)

Example 3:

Input:  distribution_center_locations = [1, 2, 5, 6]
Output: 2
Explanation:
One optimal solution is to place the warehouse at x1 = 1 and x2 = 6. Distances to the nearest warehouse for centers at [1, 2, 5, 6] are [0, 1, 1, 0]. (Updated on 02-05-2025, credit to spike :P
Constraints:
  • 1 <= n <= 2*10^3
  • 0 <= distribution_center_locations[i] <= 10^6
  • (Updated on 02-05-2025, credit to spike :D
Thumbnail 0
Thumbnail 1
Thumbnail 2
Testcase

Result
Case 1

input:

output: