CS-OA cs-vo Faang

Amazon Online Assessment: Optimal Warehouse Placement Problem

Amazon has recently established nnn 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.

Example

Suppose dist_centers = [1, 2, 3]

One optimal solution is to position the 2 warehouses at x1=1x_1 = 1x1​=1 and x2=2x_2 = 2x2​=2.

Distances to
the nearest 0 0 1
warehouse

O - Warehouse
• - Distribution center

The minimum sum of the distances between distribution centers and the warehouses closest to them is 0+0+1=10 + 0 + 1 = 10+0+1=1.

Function Description

Complete the function getMinTotalDistance in the editor below.

getMinTotalDistance has the following parameter:

  • int dist_centers[n]: the locations of the distribution centers

Returns

  • int: the minimum sum of the given expression

Constraints


Sample Input For Custom Testing

Sample Case 0

rust复制代码STDIN           FUNCTION
2               -> n = 2
1 6             -> dist_centers = [1, 6]

Sample Output

0

Explanation

Place one warehouse at x1=1x_1 = 1x1​=1 and the other at x2=6x_2 = 6x2​=6. Each center is 0 distance from its nearest warehouse.


Sample Case 1

STDIN           FUNCTION
4 -> n = 4
1 2 5 6 -> dist_centers = [1, 2, 5, 6]

Sample Output

2

Explanation

One optimal solution is to place the warehouses at x1=1x_1 = 1x1​=1 and x2=6x_2 = 6x2​=6. Distances to the nearest warehouse for centers at [1, 2, 5, 6] are [0, 0, 1, 0].

经过我们的强力面试辅助,OA代写,候选人通过这些面试题的解析和沟通,面试官不仅了解了候选人的编程能力,也看到了我在解决问题过程中清晰的思路和有效的沟通技巧。这些不仅有助于应对Amazon 的面试,同时也能提升我们解决实际编程问题的能力。祝大家面试顺利!

如果你也需要我们的面试辅助服务,请立即联系我们

Leave a Reply

Your email address will not be published. Required fields are marked *