Optimal Transfer
There are n servers in a network, arranged in ascending order of their capacities. The capacity of server i is capacity[i], and all capacity values are distinct.
The distance between server i and server j is |capacity[i] - capacity[j]|. For each server, its closest server is the one with the smallest distance in capacity, and that closest server is guaranteed to be unique.
You may perform either of the following operations from a server x:
- Connect directly to any server
yat cost|capacity[x] - capacity[y]|. - Connect to the closest server of
xat a fixed cost of1.
Given query arrays fromServer and toServer, compute the minimum cost required to connect from fromServer[i] to toServer[i] for each query. A path may be direct or may route through intermediate servers.
Complete the function minimumTransferCost in the editor below.
minimumTransferCost has the following parameters:
int[] capacity: distinct server capacities in ascending orderint[] fromServer: starting server index for each queryint[] toServer: destination server index for each query
Returns
int[]: the minimum connection cost for each query in order
1Example 1
0 -> 1, 1 -> 2, and 2 -> 1, each costing 1. So the optimal costs are 0 -> 1 -> 2 = 2, 1 -> 2 = 1, and 2 -> 1 = 1.2Example 2
0 -> 1, 1 -> 2, and 3 -> 2. The best routes are 0 -> 1 -> 2 -> 3 with cost 3, 3 -> 2 -> 1 -> 0 with cost 3, and 1 -> 2 -> 3 with cost 2.3Example 3
2 is closest to server 1, and server 1 is closest to server 0. So 2 -> 1 -> 0 costs 2, and 0 -> 1 costs 1.Constraints
Limits and guarantees your solution can rely on.
capacityis sorted in ascending order.- All values in
capacityare distinct. fromServer.length == toServer.length.