There exists an undirected and initially unrooted tree with n nodes indexed from 0 to n - 1. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
Each node has an associated price. You are given an integer array price, where price[i] is the price of the ith node.
The price sum of a given path is the sum of the prices of all nodes lying on that path.
The tree can be rooted at any node root of your choice. The incurred cost after choosing root is the difference between the maximum and minimum price sum amongst all paths starting at root.
Return the maximum possible cost amongst all possible root choices.
Example 1:
Input: n = 6, edges = [[0,1],[1,2],[1,3],[3,4],[3,5]], price = [9,8,7,6,10,5] Output: 24 Explanation: The diagram above denotes the tree after rooting it at node 2. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum. - The first path contains nodes [2,1,3,4]: the prices are [7,8,6,10], and the sum of the prices is 31. - The second path contains the node [2] with the price [7]. The difference between the maximum and minimum price sum is 24. It can be proved that 24 is the maximum cost.
Example 2:
Input: n = 3, edges = [[0,1],[1,2]], price = [1,1,1] Output: 2 Explanation: The diagram above denotes the tree after rooting it at node 0. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum. - The first path contains nodes [0,1,2]: the prices are [1,1,1], and the sum of the prices is 3. - The second path contains node [0] with a price [1]. The difference between the maximum and minimum price sum is 2. It can be proved that 2 is the maximum cost.
Constraints:
1 <= n <= 105edges.length == n - 10 <= ai, bi <= n - 1edges represents a valid tree.price.length == n1 <= price[i] <= 105When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The problem asks for the maximum difference between the maximum and minimum price path starting from any chosen root. For any chosen root, the minimum path sum is always just the root node's price, so the task simplifies to finding the maximum path sum starting from the root to some leaf node, minus the leaf node's price. This can be viewed as finding a path from the root to a leaf where one endpoint excludes its price, which can be solved efficiently using a two-pass tree rerooting dynamic programming approach.
Here's how the algorithm would work step-by-step:
def max_output(n: int, edges: list[list[int]], price: list[int]) -> int:
if n == 1:
return 0
# Build the adjacency list for the tree representation.
adjacency = [[] for _ in range(n)]
for node_u, node_v in edges:
adjacency[node_u].append(node_v)
adjacency[node_v].append(node_u)
# Compute max path sum with and without leaf for subtrees.
subtree_full = [0] * n
subtree_without_leaf = [0] * n
def dfs_bottom_up(current_node: int, parent_node: int) -> None:
current_price = price[current_node]
max_child_full = 0
max_child_without = 0
is_leaf = True
for neighbor in adjacency[current_node]:
if neighbor != parent_node:
is_leaf = False
dfs_bottom_up(neighbor, current_node)
if subtree_full[neighbor] > max_child_full:
max_child_full = subtree_full[neighbor]
if subtree_without_leaf[neighbor] > max_child_without:
max_child_without = subtree_without_leaf[neighbor]
subtree_full[current_node] = current_price + max_child_full
if is_leaf:
subtree_without_leaf[current_node] = 0
else:
subtree_without_leaf[current_node] = current_price + max_child_without
import sys
sys.setrecursionlimit(200000)
dfs_bottom_up(0, -1)
max_difference = 0
# Reroot to compute the answer for every node as root.
def dfs_reroot(current_node: int, parent_node: int, parent_full: int, parent_without: int) -> None:
nonlocal max_difference
best_paths_full = [(parent_full, parent_node)]
best_paths_without = [(parent_without, parent_node)]
for neighbor in adjacency[current_node]:
if neighbor != parent_node:
best_paths_full.append((subtree_full[neighbor], neighbor))
best_paths_without.append((subtree_without_leaf[neighbor], neighbor))
best_paths_full.sort(reverse=True)
best_paths_without.sort(reverse=True)
cost_for_node = 0
for full_val, full_neighbor in best_paths_full[:2]:
for without_val, without_neighbor in best_paths_without[:2]:
if full_neighbor != without_neighbor:
candidate = full_val
if candidate > cost_for_node:
cost_for_node = candidate
if cost_for_node > max_difference:
max_difference = cost_for_node
for neighbor in adjacency[current_node]:
if neighbor != parent_node:
chosen_full = best_paths_full[1][0] if best_paths_full[0][1] == neighbor else best_paths_full[0][0]
chosen_without = best_paths_without[1][0] if best_paths_without[0][1] == neighbor else best_paths_without[0][0]
next_parent_full = price[current_node] + chosen_full
next_parent_without = price[current_node] + chosen_without
dfs_reroot(neighbor, current_node, next_parent_full, next_parent_without)
dfs_reroot(0, -1, 0, 0)
return max_difference
The problem asks for the maximum difference between the maximum path sum and the minimum path sum starting at some root node. Because all prices are positive, the minimum path sum starting at any root is simply the price of the root node itself, and the maximum path sum must end at a leaf node. Therefore, the problem reduces to finding the maximum path sum between a root and a leaf, minus the price of the root, which is equivalent to finding a path between two nodes where one endpoint is excluded.
Here's how the algorithm would work step-by-step:
def max_price_sum(n: int, edges: list[list[int]], price: list[int]) -> int:
if n == 1:
return 0
import sys
sys.setrecursionlimit(200000)
# Build the adjacency list for the undirected tree
adjacency = [[] for _ in range(n)]
for node_u, node_v in edges:
adjacency[node_u].append(node_v)
adjacency[node_v].append(node_u)
max_cost = 0
# Helper DFS to compute the maximum path sum with and without a leaf endpoint
def dfs(current_node: int, parent_node: int) -> tuple[int, int]:
nonlocal max_cost
sum_with_leaf = price[current_node]
sum_without_leaf = 0
for neighbor in adjacency[current_node]:
if neighbor == parent_node:
continue
child_with_leaf, child_without_leaf = dfs(neighbor, current_node)
# Update the global maximum cost by combining paths through the current node
max_cost = max(max_cost, sum_with_leaf + child_without_leaf, sum_without_leaf + child_with_leaf)
sum_with_leaf = max(sum_with_leaf, price[current_node] + child_with_leaf)
sum_without_leaf = max(sum_without_leaf, price[current_node] + child_without_leaf)
return sum_with_leaf, sum_without_leaf
# Run tree traversal from an arbitrary root
dfs(0, -1)
return max_cost
| Case | How to Handle |
|---|---|
| Single node tree with no edges | The algorithm should return 0 since the maximum and minimum path sums are both equal to the single node's price. |
| Tree with negative node prices | A DFS-based path-finding approach naturally handles negative numbers by choosing not to extend a path when the accumulated sum decreases. |
| Extremely skewed linear tree resembling a linked list | Recursion depth can equal the number of nodes, requiring iterative approaches or language-specific stack limit increases to prevent stack overflow. |
| Very large integers leading to sum overflow | The solution must use 64-bit integers to accumulate path sums and prevent arithmetic overflow during calculations. |
| All node prices are identical | The algorithm must correctly compute overlapping paths and return a difference of zero when all possible path sums are equal. |
| Graph with no valid nodes or edges provided | Input validation should immediately check for empty structures and return zero or throw an appropriate argument exception. |
| Zero or mixed positive and negative pricing distributions | Using Kadane-style tree DP ensures that we properly track both maximum and minimum path sums across zero crossings. |