Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Longest Special Path

XPChallenge Points: 30
levelLevel: Hard

You are given a tree with n nodes, rooted at node 0. Each edge in the tree has a length.
You are also given an array nums, where nums[i] is the value stored at node i.

We define a special path as:

  • A path that moves downward (from parent/ancestor to child/descendant),

  • and all values of the nodes along that path must be distinct (no repeated values).

A path may consist of only one node (which means path length = 0).

Your task is to:

  • Find the maximum total length among all special paths.

  • Among all special paths that have this maximum total length, return the minimum number of nodes that appear in such a path.

Return:

[result_length, minimum_nodes_used]

Example 1:

Input: edges = [[0,1,4],[1,2,2],[2,3,3]] nums = [5,6,7,8]

Output: [9,4]

Explanation:

Path: 0 → 1 → 2 → 3 All node values are unique. Total length = 4 + 2 + 3 = 9 and 4 nodes used.

Example 2:

Input: edges = [[0,1,5],[0,2,5],[2,3,5]] nums = [1,1,2,1]

Output: [5,2]

Explanation:

Possible special paths include: - 0 → 2 → 3 is not valid because 2 and 3 share same value? No. Actually nums = [1,1,2,1] Paths: 0 (value 1) 1 (value 1) → duplicates, so cannot extend 2 (value 2) 3 (value 1) Longest valid unique path: 2 → 3, length = 5, nodes = 2

Example 3:

Input: edges = [[0,1,3]] nums = [4,4]

Output: [0,1]

Explanation:

Values repeat, so only single-node paths are allowed.

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result