Ctrl K

Route Fee Spread From the Best Start

Hard
A nature reserve has count camps numbered 0 to count − 1, linked by the trails in trails so that any two camps are joined by exactly one path (a tree). Visiting camp i costs fees[i]. Pick a starting camp s. A route is a path along the trails that starts at s and visits no camp twice; its cost is the sum of the fees of every camp on it, including s and the last one. A route may consist of s alone. The spread for start s is the difference between the most expensive and the cheapest route from s. Return the largest spread over all possible starts.
Example 1
count=5, trails=[[0, 1], [1, 2], [1, 3], [3, 4]], fees=[2, 6, 1, 3, 9] → 18

Start at camp 2: the priciest route 2 → 1 → 3 → 4 costs 1 + 6 + 3 + 9 = 19, and the cheapest is staying put for 1. The spread is 18, and no start does better.

Example 2
count=1, trails=[], fees=[7] → 0

With a single camp there is only one route, the camp itself, so the spread is 0.

Constraints
  • 1 ≤ count ≤ 10⁵
  • len(trails) = count − 1, and the trails form a tree
  • len(fees) = count
  • 1 ≤ fees[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRoots That Fit the Guesses HardDiscounted Trips Through a Tree HardHarvesting a Tree: Toll or Half HardLargest Single-Color Branch MediumHeaviest Path in a Tree Hard
loading Python…
Input
count=5, trails=[[0, 1], [1, 2], [1, 3], [3, 4]], fees=[2, 6, 1, 3, 9]
Expected
18

Run checks the first 3 tests in your browser. Submit checks all 57 tests on the server, hidden ones included.