LeetCode #3575 — HARD

Maximum Good Subtree Score

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

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.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: 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.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Dynamic Programming · Bit Manipulation · Tree

Example 1

[2,3]
[-1,0]

Example 2

[1,5,2]
[-1,0,0]

Example 3

[34,1,2]
[-1,0,1]
Step 02

Core Insight

What unlocks the optimal approach

  • Use tree dynamic programming.
  • Use bits (integer) to represent which digits are used.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3575: Maximum Good Subtree Score
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3575: Maximum Good Subtree Score
// package main
// 
// import (
// 	"maps"
// 	"slices"
// )
// 
// // https://space.bilibili.com/206214
// func goodSubtreeSum1(vals, par []int) (ans int) {
// 	const mod = 1_000_000_007
// 	const D = 10
// 	n := len(par)
// 	g := make([][]int, n)
// 	for i := 1; i < n; i++ {
// 		p := par[i]
// 		g[p] = append(g[p], i)
// 	}
// 
// 	var dfs func(int) [1 << D]int
// 	dfs = func(x int) (f [1 << D]int) {
// 		// 计算 vals[x] 的数位集合 mask
// 		mask := 0
// 		for v := vals[x]; v > 0; v /= D {
// 			d := v % D
// 			if mask>>d&1 > 0 { // d 在集合 mask 中
// 				mask = 0 // 不符合要求
// 				break
// 			}
// 			mask |= 1 << d // 把 d 加到集合 mask 中
// 		}
// 
// 		if mask > 0 {
// 			f[mask] = vals[x]
// 		}
// 
// 		// 同一个集合 i 至多选一个,直接取 max
// 		for _, y := range g[x] {
// 			fy := dfs(y)
// 			for i, sum := range fy {
// 				f[i] = max(f[i], sum)
// 			}
// 		}
// 
// 		for i := range f {
// 			// 枚举集合 i 的非空真子集
// 			for sub := i & (i - 1); sub > 0; sub = (sub - 1) & i {
// 				f[i] = max(f[i], f[sub]+f[i^sub])
// 			}
// 		}
// 
// 		ans += slices.Max(f[:])
// 		return
// 	}
// 	dfs(0)
// 	return ans % mod
// }
// 
// func goodSubtreeSumHSon(vals, par []int) (ans int) {
// 	const mod = 1_000_000_007
// 	const D = 10
// 	n := len(par)
// 	g := make([][]int, n)
// 	for i := 1; i < n; i++ {
// 		p := par[i]
// 		g[p] = append(g[p], i)
// 	}
// 
// 	var init func(int) int
// 	init = func(x int) int {
// 		if g[x] == nil {
// 			return 1
// 		}
// 		size, hsz, hIdx := 1, 0, 0
// 		for i, y := range g[x] {
// 			sz := init(y)
// 			size += sz
// 			if sz > hsz {
// 				hsz, hIdx = sz, i
// 			}
// 		}
// 		// 把重儿子换到最前面
// 		g[x][0], g[x][hIdx] = g[x][hIdx], g[x][0]
// 		return size
// 	}
// 	init(0)
// 
// 	type pair struct{ mask, val int }
// 	var dfs func(int) (map[int]int, []pair)
// 	dfs = func(x int) (f map[int]int, single []pair) {
// 		val := vals[x]
// 
// 		// 计算 val 的数位集合 mask
// 		mask := 0
// 		for v := val; v > 0; v /= D {
// 			d := v % D
// 			if mask>>d&1 > 0 {
// 				mask = 0
// 				break
// 			}
// 			mask |= 1 << d
// 		}
// 
// 		if g[x] == nil { // x 是叶子
// 			f = map[int]int{}
// 			if mask > 0 {
// 				ans += val
// 				f[mask] = val
// 				single = append(single, pair{mask, val})
// 			}
// 			return
// 		}
// 
// 		f, single = dfs(g[x][0]) // 优先遍历重儿子
// 		update := func(msk, v int) {
// 			if v <= f[msk] {
// 				return
// 			}
// 			nf := maps.Clone(f)
// 			nf[msk] = v
// 			for msk2, s2 := range f {
// 				if msk&msk2 == 0 {
// 					nf[msk|msk2] = max(nf[msk|msk2], v+s2)
// 				}
// 			}
// 			f = nf
// 		}
// 
// 		for _, y := range g[x][1:] {
// 			_, singleY := dfs(y)
// 			single = append(single, singleY...)
// 			// 把子树 y 中的 mask 和 val 一个一个地加到 f 中
// 			for _, p := range singleY {
// 				update(p.mask, p.val)
// 			}
// 		}
// 
// 		if mask > 0 {
// 			update(mask, val)
// 			single = append(single, pair{mask, val})
// 		}
// 
// 		mx := 0
// 		for _, s := range f {
// 			mx = max(mx, s)
// 		}
// 		ans += mx
// 
// 		return
// 	}
// 	dfs(0)
// 	return ans % mod
// }
// 
// func goodSubtreeSum(vals, par []int) (ans int) {
// 	const mod = 1_000_000_007
// 	const D = 10
// 	n := len(par)
// 	g := make([][]int, n)
// 	for i := 1; i < n; i++ {
// 		p := par[i]
// 		g[p] = append(g[p], i)
// 	}
// 
// 	type pair struct{ mask, val int }
// 	var dfs func(int) (map[int]int, []pair)
// 	dfs = func(x int) (f map[int]int, single []pair) {
// 		f = map[int]int{}
// 
// 		// 计算 val 的数位集合 mask
// 		val := vals[x]
// 		mask := 0
// 		for v := val; v > 0; v /= D {
// 			d := v % D
// 			if mask>>d&1 > 0 {
// 				mask = 0
// 				break
// 			}
// 			mask |= 1 << d
// 		}
// 
// 		if mask > 0 {
// 			f[mask] = val
// 			single = append(single, pair{mask, val})
// 		}
// 
// 		for _, y := range g[x] {
// 			fy, singleY := dfs(y)
// 
// 			// 启发式合并
// 			if len(singleY) > len(single) {
// 				single, singleY = singleY, single
// 				f, fy = fy, f
// 			}
// 			
// 			single = append(single, singleY...)
// 			
// 			// 把子树 y 中的 mask 和 val 一个一个地加到 f 中
// 			for _, p := range singleY {
// 				msk, v := p.mask, p.val
// 				if v <= f[msk] {
// 					continue
// 				}
// 				nf := maps.Clone(f)
// 				nf[msk] = v
// 				for msk2, s2 := range f {
// 					if msk&msk2 == 0 {
// 						nf[msk|msk2] = max(nf[msk|msk2], v+s2)
// 					}
// 				}
// 				f = nf
// 			}
// 		}
// 
// 		mx := 0
// 		for _, s := range f {
// 			mx = max(mx, s)
// 		}
// 		ans += mx
// 
// 		return
// 	}
// 	dfs(0)
// 	return ans % mod
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n × m)
Space
O(n × m)

Approach Breakdown

RECURSIVE
O(2ⁿ) time
O(n) space

Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.

DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space

Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.

Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

State misses one required dimension

Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.

Usually fails on: Correctness breaks on cases that differ only in hidden state.

Fix: Define state so each unique subproblem maps to one DP cell.

Forgetting null/base-case handling

Wrong move: Recursive traversal assumes children always exist.

Usually fails on: Leaf nodes throw errors or create wrong depth/path values.

Fix: Handle null/base cases before recursive transitions.