Taro Logo

Choose Edges to Maximize Score in a Tree

#4 Most AskedMedium
0 views
Topics:
TreesDynamic ProgrammingRecursion

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:

  • You are allowed to not choose any edges in the tree, the sum of weights in this case will be 0.
  • Two edges Edge1 and Edge2 in the tree are adjacent if they have a common node.
    • In other words, they are adjacent if 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.length
  • 1 <= n <= 105
  • edges[i].length == 2
  • par0 == weight0 == -1
  • 0 <= pari <= n - 1 for all i >= 1.
  • pari != i
  • -106 <= weighti <= 106 for all i >= 1.
  • edges represents a valid tree.

Solution


Clarifying Questions

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:

  1. Can edge weights be negative, zero, or are they guaranteed to be strictly positive?
  2. What is the maximum number of nodes in the tree, and should I expect a deeply skewed tree that could cause recursion depth issues?
  3. How is the tree structure provided to the function (e.g., an adjacency list, an array of edges, or a custom TreeNode class)?
  4. Is the tree guaranteed to be connected and acyclic, or do I need to validate the input structure?
  5. If the tree has only a single node or no edges at all, should the function return 0 as the maximum score?

Brute Force Solution

Approach

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:

  1. Construct an adjacency list from the given parent-child edge definitions.
  2. Define a recursive depth-first search function that computes two values for each node: the maximum score if the edge to its parent can be chosen, and the maximum score if the edge to its parent cannot be chosen.
  3. For each child, recursively obtain the optimal scores with and without matching that child to its own descendants.
  4. Calculate the base sum where the current node is not matched to any child, which simply takes the optimal value from each child.
  5. Iterate through the children to find if pairing the current node with any child using a positive edge weight yields a higher total score.
  6. Return the maximum value obtained for the root node.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(n) – Each node and edge in the tree is visited a constant number of times during the depth-first search traversal.
Space Complexity
O(n) – The adjacency list and the recursion call stack require linear space proportional to the number of nodes in the tree.

Optimal Solution

Approach

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:

  1. Increase the Python recursion limit to safely traverse trees with up to 100,000 nodes.
  2. Build an adjacency list representation of the directed tree from the parent pointers.
  3. Define a recursive depth-first search function that returns a pair of scores: one if the edge to the parent is used, and one if it is not used.
  4. For a given node, sum the optimal scores of all children assuming no edge to those children is selected from the current node.
  5. Find the single child edge that gives the maximum positive gain when chosen instead of skipped.
  6. Compute the optimal values for the current node and return the result calculated at the root.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n) – Each node and edge in the tree is visited exactly once during the depth-first search traversal, where n is the number of nodes.
Space Complexity
O(n) – The adjacency list and recursion call stack both require memory proportional to the number of nodes in the tree.

Edge Cases

A tree with only a single node and no edges
How to Handle:
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
How to Handle:
Dynamic programming correctly compares taking this single edge versus taking nothing and chooses the maximum
Edges with negative weights
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Using sixty-four bit integer types for score accumulation prevents potential integer overflow during summation
All edge weights are zero
How to Handle:
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
How to Handle:
Assuming valid tree structure per problem constraints, but a root parameter ensures traversal starts correctly from a designated entry point
0/45 completed