865. Non-Adjacent Tree Picks
A ranger network is a tree of n watch posts numbered 0 to n - 1, joined by n - 1 trails given as edges[i] = [a, b]. Post i has a signed score values[i]; a negative score means that post is a liability. You may activate any set of posts, including none, as long as no two activated posts are directly joined by a trail.
Return the largest possible sum of the scores of the activated posts. Activating no post gives 0. The answer can exceed the 32-bit range, so use a 64-bit integer type.
Example 1
- Input:
- n = 5edges = [[0,1],[1,2],[1,3],[3,4]]values = [5,-2,6,4,3]
- Output:
- 15
- Explanation:
Activating posts 0, 2 and 3 gives 5 + 6 + 4 = 15 and no two of them share a trail; adding any other post would break the rule (4 touches 3, 1 touches all) so 15 is the maximum.
Example 2
- Input:
- n = 3, edges = [[0,1],[1,2]], values = [4,9,4]
- Output:
- 9
- Explanation:
Activating the two outer posts gives 4 + 4 = 8 but the middle post alone scores 9, so the best is 9.
Constraints
- 1 ≤ n ≤ 105
edges.length == n - 1, 0 ≤ a, b < n and the trails form a tree- -109 ≤ values[i] ≤ 109
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 400 msC++ 100 msJava 200 msJavaScript 200 msTypeScript 200 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)