You are given a weighted tree consisting of n nodes numbered from 0 to n - 1.
The tree is rooted at node 0 and represented with a 2D array edges of size n where edges[i] = [pari, weighti] indicates that node pari is the parent of node i, and the edge between them has a weight equal to weighti. Since the root does not have a parent, you have edges[0] = [-1, -1].
Choose some edges from the tree such that no two chosen edges are adjacent and the sum of the weights of the chosen edges is maximized.
Return the maximum sum of the chosen edges.
Note:
0.Edge1 and Edge2 in the tree are adjacent if they have a common node.
Edge1 connects nodes a and b and Edge2 connects nodes b and c.Example 1:
Input: edges = [[-1,-1],[0,5],[0,10],[2,6],[2,4]] Output: 11 Explanation: The above diagram shows the edges that we have to choose colored in red. The total score is 5 + 6 = 11. It can be shown that no better score can be obtained.
Example 2:
Input: edges = [[-1,-1],[0,5],[0,-6],[0,7]] Output: 7 Explanation: We choose the edge with weight 7. Note that we cannot choose more than one edge because all edges are adjacent to each other.
Constraints:
n == edges.length1 <= n <= 105edges[i].length == 2par0 == weight0 == -10 <= pari <= n - 1 for all i >= 1.pari != i-106 <= weighti <= 106 for all i >= 1.edges represents a valid tree.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
This problem asks for the maximum weight matching in a tree. For each node, we can choose to either match it with at most one of its children or not match it with any child. We can solve this recursively using dynamic programming on trees.
Here's how the algorithm would work step-by-step:
import sys
def max_score_edges(edges):
sys.setrecursionlimit(200000)
node_count = len(edges)
# Build an adjacency list representing parent to children relationships.
adjacency = [[] for _ in range(node_count)]
for child_index in range(1, node_count):
parent_index, edge_weight = edges[child_index]
adjacency[parent_index].append((child_index, edge_weight))
# Use dynamic programming on trees with post-order traversal.
def depth_first_search(current_node):
total_best_children = 0
child_dp_results = []
for child_node, edge_weight in adjacency[current_node]:
take_child, not_take_child = depth_first_search(child_node)
best_for_child = max(take_child, not_take_child)
total_best_children += best_for_child
child_dp_results.append((child_node, edge_weight, not_take_child, best_for_child))
# Compute the case where no incident edge to a child is selected.
not_take_current = total_best_children
take_current = total_best_children
# Consider matching the current node with one of its children.
for child_node, edge_weight, not_take_child, best_for_child in child_dp_results:
if edge_weight > 0:
current_option = total_best_children - best_for_child + not_take_child + edge_weight
if current_option > take_current:
take_current = current_option
return take_current, not_take_current
take_root, not_take_root = depth_first_search(0)
return max(take_root, not_take_root)
This problem asks for the maximum weight matching in a directed tree, which is equivalent to choosing a set of non-adjacent edges with maximal total weight. We can solve this with tree dynamic programming by computing two states for each node: one where the edge connecting the node to its parent is already selected, and one where it is not. For each node, we greedily determine which child edge, if any, produces the greatest positive increase when selected.
Here's how the algorithm would work step-by-step:
import sys
def max_score_edges(edges):
# Increase recursion depth limit for deep trees
sys.setrecursionlimit(200000)
node_count = len(edges)
tree = [[] for _ in range(node_count)]
for child_index in range(1, node_count):
parent_index, weight = edges[child_index]
tree[parent_index].append((child_index, weight))
# Post-order traversal to compute DP values for each subtree
def dfs(current_node):
sum_unselected = 0
best_delta = 0
for child_node, edge_weight in tree[current_node]:
child_chosen, child_not_chosen = dfs(child_node)
sum_unselected += child_not_chosen
delta = edge_weight + child_chosen - child_not_chosen
if delta > best_delta:
best_delta = delta
chosen_value = sum_unselected
not_chosen_value = sum_unselected + best_delta
return chosen_value, not_chosen_value
# The root does not have an incoming edge, so its not_chosen_value is the answer
_, total_max_score = dfs(0)
return total_max_score
| Case | How to Handle |
|---|---|
| A tree with only a single node and no edges | The base case returns a score of zero since no edges are available to select |
| A tree consisting of a single edge connecting two nodes | Dynamic programming correctly compares taking this single edge versus taking nothing and chooses the maximum |
| Edges with negative weights | The recurrence relation allows skipping edges with negative weights by taking the maximum of excluding the edge versus including it |
| A deeply skewed tree resembling a linked list | Iterative bottom-up approaches or tail-call optimization prevent stack overflow issues common in deep recursion |
| Large scale trees with maximum constraints up to one hundred thousand nodes | An O of N time complexity linear tree traversal ensures the solution executes well within standard time limits |
| Edge weights exceeding standard thirty-two bit integer limits | Using sixty-four bit integer types for score accumulation prevents potential integer overflow during summation |
| All edge weights are zero | The algorithm handles zero weights gracefully and returns a maximum score of zero without breaking logic |
| Multiple disjoint components or forest input instead of a valid tree | Assuming valid tree structure per problem constraints, but a root parameter ensures traversal starts correctly from a designated entry point |