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
ROOTDecision PointKEEPPreserve + Optimal ChildrenTAKEValue + Preserve All ChildrenπŸ”‘ Key Insight:β€’ KEEP node β†’ Can make optimal choices in all subtreesβ€’ TAKE node β†’ Must preserve all children to keep paths healthyβ€’ Answer = max(keep_root, take_root)
Understanding the Visualization
1
Leaf Nodes
Leaves can only be taken (giving their value) or kept (giving 0)
2
Internal Nodes
For each internal node, calculate keep vs take scenarios
3
Propagate Up
Use children's optimal values to compute parent's optimal choice
4
Root Decision
The root's optimal choice gives the maximum possible score
Key Takeaway
🎯 Key Insight: Each node presents a binary choice that affects the entire subtree's optimization strategy
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