1638. Best Trail From Each Town

A region has n towns numbered 0 to n-1, joined by n - 1 two-way roads so that every town can reach every other town (the road map is a tree). Town i has a score values[i], which may be negative. Each edges[j] = [a, b] is one road.

A trail is a route along roads that never visits a town twice. For every town u, find the maximum total score of a trail that starts at u. The trail may be just the town u alone, and it may stop anywhere; the scores of all visited towns, including u, are added.

Return a long[] answer of length n where answer[u] is that maximum. When n = 1, edges is empty. Aim for O(n) time and O(n) space; the map can be a long chain, so avoid deep recursion.

Example 1

Input:
n = 4, edges = [[0,1],[1,2],[1,3]], values = [2,-3,4,-1]
Output:
[3,1,4,0]
Explanation:

From town 0 the best trail is 0, 1, 2 with 2 - 3 + 4 = 3; town 2 is best as a single town (4); town 3 should continue 3, 1, 2 for -1 - 3 + 4 = 0.

Example 2

Input:
n = 1, edges = [], values = [-5]
Output:
[-5]
Explanation:

With one town the only trail is that town.

Example 3

Input:
n = 3, edges = [[0,1],[1,2]], values = [-2,-3,-4]
Output:
[-2,-3,-4]
Explanation:

All scores are negative, so each town is best taken alone.

Constraints

1 ≤ n ≤ 5 * 104

-104 ≤ values[i] ≤ 104

edges form a tree

iterative traversal advised

DFS from every node is O(n^2)

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 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…