Tap here to switch tabs
Problem
Submissions

Problem: Maximum Good Subtree Score

med
30 min
Try to solve the Maximum Good Subtree Score problem.

Statement

You are given an integer array vals of length nn and an integer array par of length nn, representing a rooted tree with nn nodes indexed from 00 to n−1n - 1. The tree is rooted at node 00, with par[0] == -1, and for each node i where 1≤i<n1 \leq i < n, par[i] represents the parent of node i. Each node i is assigned the value vals[i].

For each node i, consider the subtree rooted at node i. A subset of nodes from this subtree is called good if each decimal digit from 00 to 99 appears at most once across the decimal representations of all values in the subset.

The score of a good subset is the sum of the values of the nodes in that subset. The score of an empty subset is 00.

Let maxScore[i] be the maximum score among all good subsets chosen from the subtree rooted at node i.

Return the sum of maxScore[i] across all nodes i from 00 to n−1n - 1.

Constraints:

  • 1≤n==1 \leq n == vals.length ≤500\leq 500

  • 1≤1 \leq vals[i] ≤109\leq 10^9

  • par.length ==n== n

  • par[0] ==−1== -1

  • 0≤0 \leq par[i] <n< n for i in [1,n−1][1, n - 1]

  • The input is generated such that the parent array par represents a valid tree.

⋮
Tap here to switch tabs
Problem
Submissions

Problem: Maximum Good Subtree Score

med
30 min
Try to solve the Maximum Good Subtree Score problem.

Statement

You are given an integer array vals of length nn and an integer array par of length nn, representing a rooted tree with nn nodes indexed from 00 to n−1n - 1. The tree is rooted at node 00, with par[0] == -1, and for each node i where 1≤i<n1 \leq i < n, par[i] represents the parent of node i. Each node i is assigned the value vals[i].

For each node i, consider the subtree rooted at node i. A subset of nodes from this subtree is called good if each decimal digit from 00 to 99 appears at most once across the decimal representations of all values in the subset.

The score of a good subset is the sum of the values of the nodes in that subset. The score of an empty subset is 00.

Let maxScore[i] be the maximum score among all good subsets chosen from the subtree rooted at node i.

Return the sum of maxScore[i] across all nodes i from 00 to n−1n - 1.

Constraints:

  • 1≤n==1 \leq n == vals.length ≤500\leq 500

  • 1≤1 \leq vals[i] ≤109\leq 10^9

  • par.length ==n== n

  • par[0] ==−1== -1

  • 0≤0 \leq par[i] <n< n for i in [1,n−1][1, n - 1]

  • The input is generated such that the parent array par represents a valid tree.