539. Maximum Subtree of the Same Color

Given a tree represented as an array edges of size (n-1), where edges[i] = [ui, vi] indicates an undirected edge between nodes ui and vi. The tree consists of n nodes labeled from 0 to n-1, with node 0 as the root. Additionally, there is also a 0-indexed integer array colors of size n, where colors[i] represents the color assigned to node i. A uniform subtree is a subtree where all nodes share the same color.

The task is to find the largest uniform subtree (in terms of the number of nodes) and return its size.

Example 1:

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

Output: 2

Explanation:

Each color is represented as:

1 -> Red

2 -> Green

3 -> Blue

The subtree rooted at node 2 contains nodes {2,3}, all of which share the same color 3. This is the largest uniform subtree with size 2.

Example 2:

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

Output: 6

Explanation:

All nodes share the same color 4. Hence, the entire tree is a uniform subtree, and its size is 6.

Now Your Turn!

Pick the correct output for the given input

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

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n <= 105
  • edges.length == n - 1
  • 0 <= ui, vi < n
  • colors[i] is an integer in a valid range
  • The input represents a valid tree structure

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
int maximumSubtreeSize(vector<vector<int>>& edges, vector<int>& colors) {
}
};
Test Case

Input:

Colors
Edges