There is an undirected tree with n nodes labeled from 0 to n - 1.
You are given a 0-indexed integer array nums of length n where nums[i] represents the value of the ith node. You are also given 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.
You are allowed to delete some edges, splitting the tree into multiple connected components. Let the value of a component be the sum of all nums[i] for which node i is in the component.
Return the maximum number of edges you can delete, such that every connected component in the tree has the same value.
Example 1:
Input: nums = [6,2,2,2,6], edges = [[0,1],[1,2],[1,3],[3,4]] Output: 2 Explanation: The above figure shows how we can delete the edges [0,1] and [3,4]. The created components are nodes [0], [1,2,3] and [4]. The sum of the values in each component equals 6. It can be proven that no better deletion exists, so the answer is 2.
Example 2:
Input: nums = [2], edges = [] Output: 0 Explanation: There are no edges to be deleted.
Constraints:
1 <= n <= 2 * 104nums.length == n1 <= nums[i] <= 50edges.length == n - 1edges[i].length == 20 <= edges[i][0], edges[i][1] <= n - 1edges represents a valid tree.When 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 number of edges to delete such that all resulting connected components have the identical sum. Deleting k edges splits the tree into k + 1 components, meaning the total sum of all node values must be divisible by k + 1. We test each possible number of components from largest to smallest and use depth-first search to check if a valid partition exists.
Here's how the algorithm would work step-by-step:
def component_value(nums: list[int], edges: list[list[int]]) -> int:
import sys
sys.setrecursionlimit(200000)
# Build the adjacency list for the tree structure.
adjacency = [[] for _ in range(len(nums))]
for node_u, node_v in edges:
adjacency[node_u].append(node_v)
adjacency[node_v].append(node_u)
total_sum = sum(nums)
max_value = max(nums)
def dfs(current_node: int, parent_node: int, target: int) -> int:
subtree_sum = nums[current_node]
for neighbor in adjacency[current_node]:
if neighbor != parent_node:
child_sum = dfs(neighbor, current_node, target)
if child_sum == -1:
return -1
subtree_sum += child_sum
if subtree_sum > target:
return -1
if subtree_sum == target:
return 0
return subtree_sum
# Iterate through possible number of components from largest to smallest.
for count in range(len(nums), 0, -1):
if total_sum % count == 0:
target = total_sum // count
# Check if each component can have this target value.
if target >= max_value and dfs(0, -1, target) == 0:
return count - 1
return 0
The problem asks for the maximum number of edge deletions such that each resulting connected component has the same sum. Deleting k edges splits the tree into k + 1 components, meaning the total sum of node values must be divisible by k + 1. We test each possible number of components from largest to smallest, verifying whether a valid partition exists using a depth-first search.
Here's how the algorithm would work step-by-step:
def component_value(nums, edges):
import sys
sys.setrecursionlimit(200000)
total_sum = sum(nums)
node_count = len(nums)
max_val = max(nums)
# Build adjacency list for tree representation
adjacency_list = [[] for _ in range(node_count)]
for u, v in edges:
adjacency_list[u].append(v)
adjacency_list[v].append(u)
def dfs(current_node, parent_node, target_value):
subtree_sum = nums[current_node]
for neighbor in adjacency_list[current_node]:
if neighbor != parent_node:
child_sum = dfs(neighbor, current_node, target_value)
if child_sum == -1:
return -1
subtree_sum += child_sum
# Cut component if subtree sum matches target
if subtree_sum == target_value:
return 0
if subtree_sum > target_value:
return -1
return subtree_sum
# Iterate through potential number of components descending
for num_components in range(node_count, 1, -1):
if total_sum % num_components == 0:
target_value = total_sum // num_components
if target_value >= max_val:
if dfs(0, -1, target_value) == 0:
return num_components - 1
return 0
| Case | How to Handle |
|---|---|
| Tree with a single node | Return zero since no edges need to be removed to have all components equal to the single node value. |
| Nodes with negative values or zero | Use post-order traversal and bottom-up summation which naturally aggregates positive, negative, and zero values correctly. |
| Deep linear trees resembling a linked list | Implement an iterative post-order traversal or increase stack limits to prevent recursion depth stack overflow errors. |
| Total sum of node values is not divisible by the component sum candidate | Only test candidate sums that evenly divide the total sum of all node values in the tree. |
| All node values are identical | The algorithm correctly identifies multiple valid partition points and minimizes deletions based on divisibility. |
| Disconnected or invalid graph inputs | Assume a valid undirected tree structure is always provided as guaranteed by standard tree problem constraints. |
| Large node values causing integer overflow during summation | Use 64-bit integer types for all sum accumulations to safely handle maximum possible cumulative values. |
| Highly skewed star-shaped tree structures | The bottom-up greedy subtree matching processes leaf nodes first, scaling efficiently in linear time. |