FastPrepFastPrep
Problem Brief

Optimal Transfer

FULLTIMENEW 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

1Example 1

Input
capacity = [2, 7, 10], fromServer = [0, 1, 2], toServer = [2, 2, 1]
Output
[2, 1, 1]
Explanation
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.

2Example 2

Input
capacity = [1, 4, 9, 15], fromServer = [0, 3, 1], toServer = [3, 0, 3]
Output
[3, 3, 2]
Explanation
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.

3Example 3

Input
capacity = [5, 6, 20], fromServer = [2, 0], toServer = [0, 1]
Output
[2, 1]
Explanation
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

Limits and guarantees your solution can rely on.

  • capacity is sorted in ascending order.
  • All values in capacity are distinct.
  • fromServer.length == toServer.length.
public int[] minimumTransferCost(int[] capacity, int[] fromServer, int[] toServer) {
  // write your code here
}
Input

capacity

[2, 7, 10]

fromServer

[0, 1, 2]

toServer

[2, 2, 1]

Output

[2, 1, 1]

Sign in to submit your solution.