#2925
Maximum Score After Applying Operations on a Tree
specialist · 930 · lc medium +32 · verified · 47.1% accepted · 366 likes · top 32%
Description
An undirected tree has n nodes labeled 0 to n - 1, rooted at 0. Edges are given in edges, and values[i] is the value assigned to node i.
You start with a score of 0. Each operation lets you:
- Pick any node i.
- Add values[i] to your score and set values[i] = 0.
The tree stays healthy as long as every path from the root to a leaf has a positive total value.
Return the highest score you can achieve without violating the health condition.
Example 1:
Input: edges = [[0,1],[0,2],[0,3],[2,4],[4,5]], values = [5,2,5,2,1,1]
Output: 11
Explanation: We can choose nodes 1, 2, 3, 4, and 5. The value of the root is non-zero. Hence, the sum of values on the path from the root to any leaf is different than zero. Therefore, the tree is healthy and the score is values[1] + values[2] + values[3] + values[4] + values[5] = 11.
It can be shown that 11 is the maximum score obtainable after any number of operations on the tree.
Example 2:
Input: edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], values = [20,10,9,7,4,3,5]
Output: 40
Explanation: We can choose nodes 0, 2, 3, and 4.
- The sum of values on the path from 0 to 4 is equal to 10.
- The sum of values on the path from 0 to 3 is equal to 10.
- The sum of values on the path from 0 to 5 is equal to 3.
- The sum of values on the path from 0 to 6 is equal to 5.
Therefore, the tree is healthy and the score is values[0] + values[2] + values[3] + values[4] = 40.
It can be shown that 40 is the maximum score obtainable after any number of operations on the tree.
Code
1
2
3