Create Components With Same Value Problem
Description
LeetCode Problem 2440.
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 i^th node. You are also given a 2D integer array edges of length n - 1 where edges[i] = [a_i, b_i] indicates that there is an edge between nodes a_i and b_i 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 * 10^4nums.length == n1 <= nums[i] <= 50edges.length == n - 1edges[i].length == 20 <= edges[i][0], edges[i][1] <= n - 1edgesrepresents a valid tree.
Solution
Approach: Enumerate the Number of Components
If the tree is split into k components, each must have value s / k, where s is the total sum, so k must divide s. Also each component holds at least the largest value mx, so k <= s / mx, and k <= n. Try k from large to small; the first one that works gives the answer k - 1 (the number of deleted edges).
To check a target t = s / k, run a DFS that returns the sum of each subtree. If a subtree sums to exactly t, cut it off and return 0 to the parent; if it sums to more than t, the target is impossible and we return -1; otherwise return the sum. The target works when the whole tree returns 0.
Complexity: The time complexity is O(n * d(s)), where d(s) is the number of divisors of the sum s, at most about sqrt(s).
from collections import defaultdict
class Solution:
def componentValue(self, nums: List[int], edges: List[List[int]]) -> int:
def dfs(i, fa):
x = nums[i]
for j in g[i]:
if j != fa:
y = dfs(j, i)
if y == -1:
return -1
x += y
if x > t:
return -1
return x if x < t else 0
n = len(nums)
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
s = sum(nums)
mx = max(nums)
for k in range(min(n, s // mx), 1, -1):
if s % k == 0:
t = s // k
if dfs(0, -1) == 0:
return k - 1
return 0