Minimum Server Connection Costs
Problem statement
There are n servers, numbered from 0 to n - 1. Server i has capacity capacity[i], and all capacities are distinct.
The closest server to i is another server with the smallest absolute capacity difference. Connecting from i to its closest server costs 1. Connecting from i to any other server j costs abs(capacity[i] - capacity[j]). The cost is directional: the closest-server relationship need not be mutual.
For each query q, find the minimum total cost to travel from server fromServer[q] to server toServer[q]. You may connect directly or route through any sequence of intermediate servers. Return the minimum costs in query order.
For this exercise, assume that a tie for closest capacity is resolved by choosing the smaller capacity. Server IDs always refer to their original positions in capacity, even if the capacities are not sorted. Connecting a server to itself requires no movement and costs 0.
Function
getMinCost(capacity: int[], fromServer: int[], toServer: int[]) → int[]Examples
Example 1
capacity = [2,7,10]fromServer = [0,1,2]toServer = [2,2,1]return = [2,1,1]The path 0 -> 1 -> 2 uses two closest-server connections and costs 1 + 1 = 2, less than the direct cost 8. Servers 1 and 2 are each other's closest servers, so the other two queries each cost 1.
Example 2
capacity = [10,2,7]fromServer = [1,0,2]toServer = [0,1,2]return = [2,6,0]In original server IDs, 1 -> 2 -> 0 costs 2. In reverse, 0 -> 2 costs 1 but 2 -> 1 costs 5, totaling 6. The last query starts and ends at server 2.
Example 3
capacity = [1,3,5]fromServer = [0,2]toServer = [2,0]return = [3,2]Server 1 is equally close to the other two servers and chooses the smaller capacity, server 0. Traveling right costs 1 + 2 = 3; traveling left costs 1 + 1 = 2.
Constraints
- For this exercise, assume
2 <= capacity.length <= 10^5. - For this exercise, assume
1 <= capacity[i] <= 10^9, and capacities are distinct. - For this exercise, assume
1 <= fromServer.length = toServer.length <= 10^5. - Every server ID in a query is between
0andcapacity.length - 1.