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.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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:
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:
0, 1, 3, 4, which has 3 good nodes and 1 bad node, resulting in a score of 3 - 1 = 2.1, 3, 4, which has 3 good nodes, resulting in a score of 3.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 <= 105edges.length == n - 1edges[i] = [ai, bi]0 <= ai, bi < ngood.length == n0 <= good[i] <= 1edges represents a valid tree.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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Tree
3 [[0,1],[1,2]] [1,0,1]
5 [[1,0],[1,2],[1,3],[3,4]] [0,1,0,1,1]
2 [[0,1]] [0,0]
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
// }
// 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
}
# Accepted solution for LeetCode #3772: Maximum Subgraph Score in a Tree
# Time: O(n)
# Space: O(n)
# bfs, tree dp
class Solution(object):
def maxSubgraphScore(self, n, edges, good):
"""
:type n: int
:type edges: List[List[int]]
:type good: List[int]
:rtype: List[int]
"""
adj = [[] for _ in xrange(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
parent = [-1]*n
q = [0]
for u in q:
for v in adj[u]:
if v == parent[u]:
continue
parent[v] = u
q.append(v)
dp = [1 if x else -1 for x in good]
for u in reversed(q):
if parent[u] == -1:
continue
dp[parent[u]] += max(dp[u], 0)
for u in q:
if parent[u] == -1:
continue
dp[u] += max(dp[parent[u]]-max(dp[u], 0), 0)
return dp
// Accepted solution for LeetCode #3772: Maximum Subgraph Score in a Tree
// Rust example auto-generated from go reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// 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
// }
// Accepted solution for LeetCode #3772: Maximum Subgraph Score in a Tree
// Auto-generated TypeScript example from go.
function exampleSolution(): void {
}
// 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
// }
Use this to step through a reusable interview workflow for this problem.
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.
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.
Review these before coding to avoid predictable interview regressions.
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.
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.
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.