Taro Logo

Maximum Good Subtree Score

#51 Most AskedHard
0 views
Topics:
ArraysTreesRecursionDynamic Programming, Bit Manipulation

You are given an undirected tree rooted at node 0 with n nodes numbered from 0 to n - 1. Each node i has an integer value vals[i], and its parent is given by par[i].

A subset of nodes within the subtree of a node is called good if every digit from 0 to 9 appears at most once in the decimal representation of the values of the selected nodes.

The score of a good subset is the sum of the values of its nodes.

Define an array maxScore of length n, where maxScore[u] represents the maximum possible sum of values of a good subset of nodes that belong to the subtree rooted at node u, including u itself and all its descendants.

Return the sum of all values in maxScore.

Since the answer may be large, return it modulo 109 + 7.

Example 1:

Input: vals = [2,3], par = [-1,0]

Output: 8

Explanation:

  • The subtree rooted at node 0 includes nodes {0, 1}. The subset {2, 3} is good as the digits 2 and 3 appear only once. The score of this subset is 2 + 3 = 5.
  • The subtree rooted at node 1 includes only node {1}. The subset {3} is good. The score of this subset is 3.
  • The maxScore array is [5, 3], and the sum of all values in maxScore is 5 + 3 = 8. Thus, the answer is 8.

Example 2:

Input: vals = [1,5,2], par = [-1,0,0]

Output: 15

Explanation:

  • The subtree rooted at node 0 includes nodes {0, 1, 2}. The subset {1, 5, 2} is good as the digits 1, 5 and 2 appear only once. The score of this subset is 1 + 5 + 2 = 8.
  • The subtree rooted at node 1 includes only node {1}. The subset {5} is good. The score of this subset is 5.
  • The subtree rooted at node 2 includes only node {2}. The subset {2} is good. The score of this subset is 2.
  • The maxScore array is [8, 5, 2], and the sum of all values in maxScore is 8 + 5 + 2 = 15. Thus, the answer is 15.

Example 3:

Input: vals = [34,1,2], par = [-1,0,1]

Output: 42

Explanation:

  • The subtree rooted at node 0 includes nodes {0, 1, 2}. The subset {34, 1, 2} is good as the digits 3, 4, 1 and 2 appear only once. The score of this subset is 34 + 1 + 2 = 37.
  • The subtree rooted at node 1 includes node {1, 2}. The subset {1, 2} is good as the digits 1 and 2 appear only once. The score of this subset is 1 + 2 = 3.
  • The subtree rooted at node 2 includes only node {2}. The subset {2} is good. The score of this subset is 2.
  • The maxScore array is [37, 3, 2], and the sum of all values in maxScore is 37 + 3 + 2 = 42. Thus, the answer is 42.

Example 4:

Input: vals = [3,22,5], par = [-1,0,1]

Output: 18

Explanation:

  • The subtree rooted at node 0 includes nodes {0, 1, 2}. The subset {3, 22, 5} is not good, as digit 2 appears twice. Therefore, the subset {3, 5} is valid. The score of this subset is 3 + 5 = 8.
  • The subtree rooted at node 1 includes nodes {1, 2}. The subset {22, 5} is not good, as digit 2 appears twice. Therefore, the subset {5} is valid. The score of this subset is 5.
  • The subtree rooted at node 2 includes {2}. The subset {5} is good. The score of this subset is 5.
  • The maxScore array is [8, 5, 5], and the sum of all values in maxScore is 8 + 5 + 5 = 18. Thus, the answer is 18.

Constraints:

  • 1 <= n == vals.length <= 500
  • 1 <= vals[i] <= 109
  • par.length == n
  • par[0] == -1
  • 0 <= par[i] < n for i in [1, n - 1]
  • The input is generated such that the parent array par 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 node weights and node values be negative, zero, or only positive integers?
  2. What data types are used for the node weights and values (e.g., standard 32-bit integers, 64-bit integers), and can they exceed standard integer limits when summed up?
  3. Could the input tree be empty (i.e., root is null), and in that case, what should the returned score be?
  4. When we define a subtree as 'good' if all its node values are distinct, does a duplicate value in a parent node invalidate the entire subtree below it, or just subtrees containing that duplicate?
  5. Are the node values globally unique within the entire binary tree, or is 'distinct' strictly checked per individual subtree path/branch?

Brute Force Solution

Approach

This problem requires finding the maximum score of a good subset of nodes for each subtree in a given tree. A subset is good if no digit appears more than once across all selected node values. We can model this by representing the digits of each node as a 10-bit bitmask and using dynamic programming over the bitmasks for each subtree.

Here's how the algorithm would work step-by-step:

  1. Precompute the digit bitmask for each node value, flagging values that have duplicate digits within themselves as invalid.
  2. Construct an adjacency list representing tree children and determine a post-order traversal using topological ordering.
  3. Gather all descendant nodes for each node bottom-up by combining lists of its children.
  4. For each node, perform dynamic programming over the 1024 possible digit bitmasks using all nodes in its subtree to find the maximum sum.
  5. Record the maximum score obtainable for each subtree, and return the sum of all subtree maximum scores modulo 10^9 + 7.

Code Implementation

def maximum_good_subtree_score(vals: list[int], par: list[int]) -> int:
    modulo = 10**9 + 7
    total_nodes = len(vals)
    children = [[] for _ in range(total_nodes)]
    for node_index in range(1, total_nodes):
        children[par[node_index]].append(node_index)
    
    # Precompute digit bitmask and check if individual node values have duplicate digits
    node_masks = []
    for val in vals:
        mask = 0
        is_valid = True
        for ch in str(val):
            digit_bit = 1 << int(ch)
            if mask & digit_bit:
                is_valid = False
                break
            mask |= digit_bit
        node_masks.append(mask if is_valid else -1)
    
    # Order nodes topologically from leaves to root for bottom-up processing
    order = []
    queue = [0]
    while queue:
        curr = queue.pop()
        order.append(curr)
        for child in children[curr]:
            queue.append(child)
    order.reverse()
    
    # Subtree elements collection to run bitmask DP for each node's subtree
    subtree_nodes = [[] for _ in range(total_nodes)]
    max_scores = [0] * total_nodes
    
    for curr in order:
        curr_list = [curr]
        for child in children[curr]:
            curr_list.extend(subtree_nodes[child])
        subtree_nodes[curr] = curr_list
        
        # Find the maximum score using 10-bit digit mask dynamic programming
        dp = {0: 0}
        for node in curr_list:
            mask = node_masks[node]
            if mask == -1:
                continue
            val = vals[node]
            updates = {}
            for existing_mask, current_score in dp.items():
                if not (existing_mask & mask):
                    new_mask = existing_mask | mask
                    new_score = current_score + val
                    if new_score > updates.get(new_mask, dp.get(new_mask, -1)):
                        updates[new_mask] = new_score
            for new_mask, new_score in updates.items():
                if new_score > dp.get(new_mask, -1):
                    dp[new_mask] = new_score
        max_scores[curr] = max(dp.values())
        
    return sum(max_scores) % modulo

Big(O) Analysis

Time Complexity
O(n^2 * 2^10) – There are n nodes. In the worst case (a linear tree), each node has up to n subtree elements. For each subtree, we iterate through its elements and update up to 2^10 = 1024 mask states. With n = 500, the maximum number of DP operations is bounded and runs efficiently within limits.
Space Complexity
O(n^2 + 2^10) – Storing the subtree node lists requires up to O(n^2) space in the worst case, and the DP dictionary holds at most 2^10 = 1024 entries.

Optimal Solution

Approach

This problem requires finding the maximum sum of a subset of nodes in each subtree such that no digit 0 through 9 appears more than once across the chosen nodes. Each number's digits can be represented as a bitmask of length 10, or marked invalid if it has duplicate digits. For each subtree, we can solve a 0/1 knapsack-like dynamic programming problem over the 1024 possible digit bitmasks.

Here's how the algorithm would work step-by-step:

  1. Precompute a 10-bit digit mask for each node's value, marking nodes with repeating digits as invalid.
  2. Construct the tree structure and collect all nodes belonging to each node's subtree using a post-order traversal.
  3. For every subtree, initialize a DP table of size 1024 tracking the maximum achievable value for each subset of digits.
  4. Iterate over each valid node in the subtree and update the DP table backwards to ensure each node is used at most once.
  5. Find the maximum value achieved across all states for each subtree, and accumulate these subtree scores modulo 10^9 + 7.

Code Implementation

def max_good_subtree_score(vals: list[int], par: list[int]) -> int:
    num_nodes = len(vals)
    children = [[] for _ in range(num_nodes)]
    for node_idx in range(1, num_nodes):
        children[par[node_idx]].append(node_idx)

    # Precompute the bitmask for each node's value based on unique digits.
    masks = [0] * num_nodes
    for node_idx, val in enumerate(vals):
        current_mask = 0
        is_valid = True
        temp_val = val
        while temp_val > 0:
            digit = temp_val % 10
            if (current_mask >> digit) & 1:
                is_valid = False
                break
            current_mask |= 1 << digit
            temp_val //= 10
        masks[node_idx] = current_mask if is_valid else -1

    # Order nodes post-order to process subtrees bottom-up.
    order = []
    stack = [0]
    visited_children = [0] * num_nodes
    while stack:
        current = stack[-1]
        child_idx = visited_children[current]
        if child_idx < len(children[current]):
            stack.append(children[current][child_idx])
            visited_children[current] += 1
        else:
            order.append(stack.pop())

    subtree_nodes = [[] for _ in range(num_nodes)]
    for current in order:
        node_list = [current]
        for child in children[current]:
            node_list.extend(subtree_nodes[child])
        subtree_nodes[current] = node_list

    total_sum = 0
    modulo = 10**9 + 7

    # Run knapsack-style DP over digit masks for each node's subtree.
    for current in range(num_nodes):
        dp = [-1] * 1024
        dp[0] = 0
        for member in subtree_nodes[current]:
            mask = masks[member]
            if mask == -1:
                continue
            val = vals[member]
            # Update the maximum score for each combined mask without overlapping digits.
            for state in range(1023, -1, -1):
                if dp[state] != -1 and (state & mask) == 0:
                    new_state = state | mask
                    if dp[state] + val > dp[new_state]:
                        dp[new_state] = dp[state] + val
        total_sum = (total_sum + max(dp)) % modulo

    return total_sum

Big(O) Analysis

Time Complexity
O(n^2 * 2^10) – There are n nodes. In the worst case, each subtree contains up to n nodes, and for each node in a subtree, we iterate over 2^10 = 1024 bitmask states. Thus, the total time complexity is bounded by O(n^2 * 1024), which is roughly 500^2 * 1024 operations and well within the time limit.
Space Complexity
O(n^2) – Storing the subtree nodes for all n subtrees takes at most O(n^2) space in the worst case, and the DP table and precomputed masks require O(2^10 + n) auxiliary space.

Edge Cases

Null or empty root node representing an empty tree
How to Handle:
Return a score of zero immediately since no valid subtrees exist.
Tree with a single node
How to Handle:
Return the weight of that single node as the maximum score since a one-node subtree trivially has distinct values.
Duplicate values present in different nodes of the same subtree
How to Handle:
Aggregate values using a set during recursion to invalidate the subtree and prevent its score from propagating upwards.
Negative weights assigned to tree nodes
How to Handle:
Allow negative scores in the recursion and ensure the global maximum tracker correctly captures smaller or zero values if all subtrees yield negative sums.
Extremely skewed or linear tree structure resembling a linked list
How to Handle:
Ensure the recursion depth matches the tree height, avoiding stack overflow by optimizing or relying on language-standard deep recursion limits for N equals 100,000.
Integer overflow from summing very large node weights
How to Handle:
Use 64-bit integers for all weight and score accumulations to prevent overflow during depth-first search summation.
All nodes in the tree having identical values
How to Handle:
Restrict valid good subtrees strictly to individual leaf nodes, returning the maximum single node weight as the final answer.
0/257 completed