Maximum Score After Applying Operations on a Tree - Problem

Imagine you're a resource collector in a mystical tree where each node contains valuable points. You can collect points from any node, but there's a crucial constraint: the tree must remain "healthy".

Given an undirected tree with n nodes (labeled 0 to n-1) rooted at node 0, you need to:

  • Collect points from nodes to maximize your score
  • Ensure every path from root to any leaf has a non-zero sum (healthy tree)

Operations: Pick any node, add its value to your score, then set that node's value to 0.

Goal: Find the maximum score while keeping the tree healthy!

Example: If you have a path root→leaf with values [5, 3, 2], you can collect at most 2 nodes' values (leaving at least one non-zero for health).

Input & Output

example_1.py — Simple Tree
$ Input: edges = [[0,2],[1,2],[1,3],[2,4]] values = [1,2,3,4,5]
Output: 6
💡 Note: We can take nodes 1 and 4 (values 2+4=6). The paths remain healthy: [3→3→2] sum=5, [3→3→0→5] sum=8, [3→2] sum=5. All paths have non-zero sums.
example_2.py — Linear Tree
$ Input: edges = [[0,1],[1,2],[2,3]] values = [10,5,3,1]
Output: 15
💡 Note: We can take nodes 0, 1, and 2 (values 10+5+3=18), but this makes the path sum 0. Instead, take nodes 0 and 1 (10+5=15), leaving path [0→3→1] with sum=4.
example_3.py — Single Node
$ Input: edges = [] values = [5]
Output: 0
💡 Note: With only one node (the root), we cannot take it because then the path from root to itself would have sum 0, making the tree unhealthy.

Constraints

  • 1 ≤ n ≤ 2 × 104
  • edges.length == n - 1
  • 0 ≤ ai, bi < n
  • All edges are distinct and form a valid tree
  • 1 ≤ values[i] ≤ 104

Visualization

Tap to expand
Maximum Score After Operations on Tree INPUT Tree Structure (rooted at 0) 0 v=1 2 v=3 1 v=2 4 v=5 3 v=4 edges=[[0,2],[1,2],[1,3],[2,4]] values = [1,2,3,4,5] ALGORITHM STEPS 1 DFS Tree Traversal Compute subtree sums 2 Health Constraint Keep min value per path 3 DP Calculation max(take,leave) per node 4 Optimal Selection Collect max while healthy Subtree Analysis Node 3: leaf, sum=4 Node 4: leaf, sum=5 Node 1: sum=2+4=6 Node 2: sum=3+6+5=14 Node 0: sum=1+14=15 Total - min_per_path = 6 FINAL RESULT Optimal Collection Strategy 0 KEEP 2 TAKE 1 TAKE 4 KEEP 3 KEEP TAKE (collected) KEEP (healthy path) Output 6 Score: 3 + 2 + 1 = 6 Key Insight: For each root-to-leaf path, we must keep at least one non-zero node. The optimal strategy is to keep the MINIMUM value node on each path and collect all others. Use DFS + DP to find the maximum collectible sum = Total Sum - (minimum values needed to keep paths healthy). TutorialsPoint - Maximum Score After Applying Operations on a Tree | Optimal Solution
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
34.8K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen