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:

{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.{1}. The subset {3} is good. The score of this subset is 3.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:

{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.{1}. The subset {5} is good. The score of this subset is 5.{2}. The subset {2} is good. The score of this subset is 2.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:

{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.{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.{2}. The subset {2} is good. The score of this subset is 2.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:
{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.{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.{2}. The subset {5} is good. The score of this subset is 5.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 <= 5001 <= vals[i] <= 109par.length == npar[0] == -10 <= par[i] < n for i in [1, n - 1]par 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 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:
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
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:
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
| Case | How to Handle |
|---|---|
| Null or empty root node representing an empty tree | Return a score of zero immediately since no valid subtrees exist. |
| Tree with a single node | 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 | Aggregate values using a set during recursion to invalidate the subtree and prevent its score from propagating upwards. |
| Negative weights assigned to tree nodes | 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 | 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 | 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 | Restrict valid good subtrees strictly to individual leaf nodes, returning the maximum single node weight as the final answer. |