Optimal Transfer
Learn this problemProblem statement
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.
Function
minimumTransferCost(capacity: int[], fromServer: int[], toServer: int[]) → int[]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
Examples
Example 1
capacity = [2, 7, 10]fromServer = [0, 1, 2]toServer = [2, 2, 1]return = [2, 1, 1]The closest edges are 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.
Example 2
capacity = [1, 4, 9, 15]fromServer = [0, 3, 1]toServer = [3, 0, 3]return = [12, 3, 11]The directed closest-server edges are 0 -> 1, 1 -> 0, 2 -> 1, and 3 -> 2. Therefore 0 -> 3 costs 1 + 5 + 6 = 12, 3 -> 0 costs 1 + 1 + 1 = 3, and 1 -> 3 costs 5 + 6 = 11.
Example 3
capacity = [5, 6, 20]fromServer = [2, 0]toServer = [0, 1]return = [2, 1]Server 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
capacityis sorted in ascending order.- All values in
capacityare distinct. fromServer.length == toServer.length.