763. Good Paths
A hiking area has n campsites numbered 0 to n - 1, joined by n - 1 two-way trails given in edges so that every campsite can be reached from every other. Campsite i has a rating values[i].
A walk along trails that never visits a campsite twice is scenic when its two end campsites have the same rating and no campsite on the walk has a higher rating than that. A walk made of a single campsite is scenic. A walk from a to b is the same walk as from b to a, so count it once. Return the number of scenic walks. The result is guaranteed to fit in a 32-bit signed integer.
Example 1
- Input:
- values = [1,3,2,1,3], edges = [[0,1],[0,2],[2,3],[2,4]]
- Output:
- 6
- Explanation:
Five single camps, plus the two rating-3 camps 1 and 4 whose path 1-0-2-4 never exceeds 3; the rating-1 camps 0 and 3 are separated by the higher camp 2.
Example 2
- Input:
- values = [2,2,2], edges = [[0,1],[1,2]]
- Output:
- 6
- Explanation:
Three single camps and all three pairs (0,1), (1,2), (0,2) have equal ratings along the whole route: 3 + 3 = 6.
Example 3
- Input:
- values = [5], edges = []
- Output:
- 1
- Explanation:
One camp is one scenic route on its own.
Constraints
- 1 ≤ n ≤ 5 * 104
edges.length == n - 1and the trails form a tree- 0 ≤ values[i] ≤ 105
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 300 msC++ 75 msJava 150 msJavaScript 150 msTypeScript 150 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)