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
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
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code