LeetCode #3772 — HARD

Maximum Subgraph Score in a Tree

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 with n nodes, numbered from 0 to n - 1. It is represented by a 2D integer array edges​​​​​​​ of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

You are also given an integer array good of length n, where good[i] is 1 if the ith node is good, and 0 if it is bad.

Define the score of a subgraph as the number of good nodes minus the number of bad nodes in that subgraph.

For each node i, find the maximum possible score among all connected subgraphs that contain node i.

Return an array of n integers where the ith element is the maximum score for node i.

A subgraph is a graph whose vertices and edges are subsets of the original graph.

A connected subgraph is a subgraph in which every pair of its vertices is reachable from one another using only its edges.

Example 1:

Input: n = 3, edges = [[0,1],[1,2]], good = [1,0,1]

Output: [1,1,1]

Explanation:

  • Green nodes are good and red nodes are bad.
  • For each node, the best connected subgraph containing it is the whole tree, which has 2 good nodes and 1 bad node, resulting in a score of 1.
  • Other connected subgraphs containing a node may have the same score.

Example 2:

Input: n = 5, edges = [[1,0],[1,2],[1,3],[3,4]], good = [0,1,0,1,1]

Output: [2,3,2,3,3]

Explanation:

  • Node 0: The best connected subgraph consists of nodes 0, 1, 3, 4, which has 3 good nodes and 1 bad node, resulting in a score of 3 - 1 = 2.
  • Nodes 1, 3, and 4: The best connected subgraph consists of nodes 1, 3, 4, which has 3 good nodes, resulting in a score of 3.
  • Node 2: The best connected subgraph consists of nodes 1, 2, 3, 4, which has 3 good nodes and 1 bad node, resulting in a score of 3 - 1 = 2.

Example 3:

Input: n = 2, edges = [[0,1]], good = [0,0]

Output: [-1,-1]

Explanation:

For each node, including the other node only adds another bad node, so the best score for both nodes is -1.

Constraints:

  • 2 <= n <= 105
  • edges.length == n - 1
  • edges[i] = [ai, bi]
  • 0 <= ai, bi < n
  • good.length == n
  • 0 <= good[i] <= 1
  • The input is generated such that edges 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 with n nodes, numbered from 0 to n - 1. It is represented by a 2D integer array edges​​​​​​​ of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. You are also given an integer array good of length n, where good[i] is 1 if the ith node is good, and 0 if it is bad. Define the score of a subgraph as the number of good nodes minus the number of bad nodes in that subgraph. For each node i, find the maximum possible score among all connected subgraphs that contain node i. Return an array of n integers where the ith element is the maximum score for node i. A subgraph is a graph whose vertices and edges are subsets of the original graph. A connected subgraph is a subgraph in which every pair of its vertices is reachable from one another using only its edges.

Baseline thinking

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

Pattern signal: Array · Dynamic Programming · Tree

Example 1

3
[[0,1],[1,2]]
[1,0,1]

Example 2

5
[[1,0],[1,2],[1,3],[3,4]]
[0,1,0,1,1]

Example 3

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

Core Insight

What unlocks the optimal approach

  • Use rerooting dynamic programming
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 #3772: Maximum Subgraph Score in a Tree
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3772: Maximum Subgraph Score in a Tree
// package main
// 
// // https://space.bilibili.com/206214
// func maxSubgraphScore1(n int, edges [][]int, good []int) []int {
// 	g := make([][]int, n)
// 	for _, e := range edges {
// 		x, y := e[0], e[1]
// 		g[x] = append(g[x], y)
// 		g[y] = append(g[y], x)
// 	}
// 
// 	// subScore[x] 表示(以 0 为根时)包含 x 的子树 x 的最大得分(注意是子树不是子图)
// 	subScore := make([]int, n)
// 	// 计算 subScore[x]
// 	var dfs func(int, int)
// 	dfs = func(x, fa int) {
// 		subScore[x] = good[x]*2 - 1 // subScore[x] 一定包含 x
// 		for _, y := range g[x] {
// 			if y != fa {
// 				dfs(y, x)
// 				// 如果子树 y 的最大得分 > 0,选子树 y,否则不选
// 				subScore[x] += max(subScore[y], 0)
// 			}
// 		}
// 	}
// 	dfs(0, -1)
// 
// 	ans := make([]int, n)
// 	ans[0] = subScore[0]
// 	// 对于 x 的儿子 y,计算包含 y 的子图最大得分
// 	var reroot func(int, int)
// 	reroot = func(x, fa int) {
// 		for _, y := range g[x] {
// 			if y != fa {
// 				// 从 ans[x] 中去掉子树 y。换根后,这部分内容变成 y 的一棵子树(记作 F)
// 				scoreF := ans[x] - max(subScore[y], 0)
// 				// 如果子树 F 的最大得分 > 0,选子树 F,否则不选
// 				ans[y] = subScore[y] + max(scoreF, 0)
// 				reroot(y, x)
// 			}
// 		}
// 	}
// 	reroot(0, -1)
// 	return ans
// }
// 
// func maxSubgraphScore(n int, edges [][]int, ans []int) []int {
// 	g := make([][]int, n)
// 	for _, e := range edges {
// 		x, y := e[0], e[1]
// 		g[x] = append(g[x], y)
// 		g[y] = append(g[y], x)
// 	}
// 
// 	var dfs func(int, int)
// 	dfs = func(x, fa int) {
// 		ans[x] = ans[x]*2 - 1
// 		for _, y := range g[x] {
// 			if y != fa {
// 				dfs(y, x)
// 				// 如果子树 y 的最大得分 > 0,选子树 y,否则不选
// 				ans[x] += max(ans[y], 0)
// 			}
// 		}
// 	}
// 	dfs(0, -1)
// 
// 	// 对于 x 的儿子 y,计算包含 y 的子图最大得分
// 	var reroot func(int, int)
// 	reroot = func(x, fa int) {
// 		for _, y := range g[x] {
// 			if y != fa {
// 				// 从 ans[x] 中去掉子树 y。换根后,这部分内容变成 y 的一棵子树(记作 F)
// 				scoreF := ans[x] - max(ans[y], 0)
// 				// 如果子树 F 的最大得分 > 0,选子树 F,否则不选
// 				ans[y] += max(scoreF, 0)
// 				reroot(y, x)
// 			}
// 		}
// 	}
// 	reroot(0, -1)
// 	return ans
// }
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.