← 返回 citadel 的题目列表Maximum Path Sum in a Tree
类型:online_judge
Given a tree represented as an array, each node has a value which can be positive or negative. Find the maximum path value starting from any node u, where the path can only move from parent to child node, not in reverse order. Use depth-first search (DFS) to solve.
Input:
nodes: An array of integers containing the value of each node.
children: A 2D array representing parent-child relationships, where children[i] is the array of children for parent node i.
Output:
An integer representing the maximum path sum.
Example:
Input:
nodes = [1, -2, 3, 4, -5, 6]
children = [[1, 2], [3, 4], [5], [], [], []]
Output: 10
Explanation: The maximum path is 3 -> 6 with path sum 3 + 6 = 10.
Constraints:
Number of nodes in tree n <= 10^5
Node values range from -10^4 to 10^4
Example
Input
nodes = [1, -2, 3, 4, -5, 6]
children = [[1, 2], [3, 4], [5], [], [], []]