Problem · Graph

Optimal Transfer

HardSuperhumanFULLTIMENEW GRADOA

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 y at cost |capacity[x] - capacity[y]|.
  • Connect to the closest server of x at a fixed cost of 1.

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 Description

Complete the function minimumTransferCost in the editor below.

minimumTransferCost has the following parameters:

  • int[] capacity: distinct server capacities in ascending order
  • int[] fromServer: starting server index for each query
  • int[] toServer: destination server index for each query

Returns

int[]: the minimum connection cost for each query in order

Examples
01 · 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.
02 · Example 2
capacity = [1, 4, 9, 15]
fromServer = [0, 3, 1]
toServer = [3, 0, 3]
return = [3, 3, 2]
Closest-server hops form a cheap chain: 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.
03 · 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
  • capacity is sorted in ascending order.
  • All values in capacity are distinct.
  • fromServer.length == toServer.length.
More Superhuman problems
drafts saved locally
public int[] minimumTransferCost(int[] capacity, int[] fromServer, int[] toServer) {
  // write your code here
}
capacity[2, 7, 10]
fromServer[0, 1, 2]
toServer[2, 2, 1]
expected[2, 1, 1]
checking account