Monitoring~22 min2s · 256 MBtarget O(n) time, O(n) spacedfs
You work on a monitoring system for a company's internal services. The services are connected by links so that there is exactly one route between any two services, which makes the network a tree. Each link has a latency in milliseconds.
Your team lead asks: "What is the slowest route between any two services?" The route's latency is the sum of the latencies of its links. The network can hold 100,000 services, and a latency can be up to 100,000 ms.
Write slowest_route(n, links).
n is the number of services, numbered 0 to n - 1.links[i] = [a, b, ms] joins services a and b with a latency of ms milliseconds. There are exactly n - 1 links, and every service can reach every other.With one service there is no route, so the answer is 0.
Input: n = 6, links = [[0, 1, 4], [1, 2, 3], [1, 3, 5], [3, 4, 2], [3, 5, 6]]
Output: 15| Route between | Links used | Latency |
|---|---|---|
| 0 and 5 | 0-1, 1-3, 3-5 | 4 + 5 + 6 = 15 |
| 2 and 5 | 2-1, 1-3, 3-5 | 3 + 5 + 6 = 14 |
| 0 and 4 | 0-1, 1-3, 3-4 | 4 + 5 + 2 = 11 |
| 4 and 5 | 4-3, 3-5 | 2 + 6 = 8 |
No other route is slower than 15.
Input: n = 5, links = [[0, 1, 1], [1, 2, 1], [0, 3, 100], [0, 4, 100]]
Output: 200The route from 3 to 4 passes through service 0 and has only 2 links, but it is the slowest. The longest chain, from 2 to 3, has 3 links and only 102 ms.
Input: n = 1, links = []
Output: 01 ≤ n ≤ 100,0000 ≤ len(links) < n, with exactly n - 1 links forming one tree.1 ≤ ms ≤ 100,000Starting a walk from every service takes about 10,000,000,000 steps, because each walk visits all 100,000 services. A network can also be a chain of 100,000 services, which is too deep for a recursive walk in some languages. A method that walks the tree twice, with a stack of its own, needs about 200,000 steps.