Maximum Subtree of the Same Color Problem
Description
LeetCode Problem 3004.
You are given a 2D integer array edges representing a tree with n nodes, numbered from 0 to n - 1, rooted at node 0, where edges[i] = [u_i, v_i] means there is an edge between the nodes v_i and u_i.
You are also given a 0-indexed integer array colors of size n, where colors[i] is the color assigned to node i.
We want to find a node v such that every node in the subtree of v has the same color.
Return the size of such subtree with the maximum number of nodes possible.

Example 1:
Input: edges = [[0,1],[0,2],[0,3]], colors = [1,1,2,3]
Output: 1
Explanation: Each color is represented as: 1 -> Red, 2 -> Green, 3 -> Blue. We can see that the subtree rooted at node 0 has children with different colors. Any other subtree is of the same color and has a size of 1. Hence, we return 1.
Example 2:
Input: edges = [[0,1],[0,2],[0,3]], colors = [1,1,1,1]
Output: 4
Explanation: The whole tree has the same color, and the subtree rooted at node 0 has the most number of nodes which is 4. Hence, we return 4.

Example 3:
Input: edges = [[0,1],[0,2],[2,3],[2,4]], colors = [1,2,3,3,3]
Output: 3
Explanation: Each color is represented as: 1 -> Red, 2 -> Green, 3 -> Blue. We can see that the subtree rooted at node 0 has children with different colors. Any other subtree is of the same color, but the subtree rooted at node 2 has a size of 3 which is the maximum. Hence, we return 3.
Constraints:
n == edges.length + 11 <= n <= 5 * 10^4edges[i] == [u_i, v_i]0 <= u_i, v_i < ncolors.length == n1 <= colors[i] <= 10^5- The input is generated such that the graph represented by
edgesis a tree.
Solution
Approach: DFS
Build the adjacency list and root the tree at node 0. A DFS returns whether the subtree of a node is one color, and also accumulates subtree sizes. A node's subtree is monochromatic when every child's subtree is monochromatic and every child has the same color as the node. Whenever that holds, update the answer with the subtree size.
Complexity: O(n) time and O(n) space.
class Solution:
def maximumSubtreeSize(self, edges: List[List[int]], colors: List[int]) -> int:
def dfs(a: int, fa: int) -> bool:
ok = True
for b in g[a]:
if b != fa:
t = dfs(b, a)
ok = ok and colors[a] == colors[b] and t
size[a] += size[b]
if ok:
nonlocal ans
ans = max(ans, size[a])
return ok
n = len(edges) + 1
g = [[] for _ in range(n)]
size = [1] * n
for a, b in edges:
g[a].append(b)
g[b].append(a)
ans = 0
dfs(0, -1)
return ans