Maximum Path with the Same Labels

Consider an undirected tree with N nodes, numbered 1..N. Each node has a label associated with it, which is an integer value. Different nodes can have the same label. You are given a zero indexed array A of length N, where A[j] is the label value of the (j + 1)th node in the tree, and a zero-indexed array E of length K = (N – 1) * 2 in which the edges of the tree are described. You should returns the length of the longest path such that all the nodes on that path have the same label. The length is the number of edges in that path.

Example:

A = [1, 1, 1, 2, 2] means that nodes 1, 2, 3 have label 1; nodes 4, 5 have label 2.

E = [1, 2, 1, 3, 2, 4, 2, 5] means that the edges are (1, 2), (1, 3), (2, 4), (2, 5).

Then, the function should return 2 since the longest path with the same label is 2 > 1 > 3.

Contributed by Berkan Teber