Subtree Inversion Sum II Problem
Description
LeetCode Problem 3949.
You are given an undirected tree rooted at node 0, with n nodes numbered from 0 to n - 1. The tree is represented by a 2D integer array edges of length n - 1, where edges[i] = [u_i, v_i] indicates an edge between nodes u_i and v_i.
You are also given an integer array nums of length n, where nums[i] represents the value at node i, and an integer k.
You may perform inversion operations on a subset of nodes subject to the following rules:
- Subtree Inversion Operation:
- When you invert a node, every value in the subtree rooted at that node is multiplied by -1.
- Distance Constraint on Inversions:
- You may only invert a node if it is “sufficiently far” from any other inverted node.
- If you invert two nodes
aandb, the distance (the number of edges on the unique path between them) must be at leastk.
Return the maximum possible sum of the tree’s node values after applying inversion operations.
Example 1:
Input: edges = [[0,1],[0,2],[0,3],[1,4],[1,5]], nums = [1,0,-10,3,4,5], k = 2
Output: 23
Explanation:

After inverting the subtree rooted at node 2, the maximum sum becomes 1 + 0 + 10 + 3 + 4 + 5 = 23.
Example 2:
Input: edges = [[0,1],[1,2]], nums = [5,-10,-10], k = 1
Output: 25
Explanation:

After inverting the subtree rooted at node 1, the maximum sum becomes 5 + 10 + 10 = 25.
Example 3:
Input: edges = [[0,1],[0,2]], nums = [1,-5,-6], k = 2
Output: 12
Explanation:

- After inverting the subtrees rooted at nodes 1 and 2, nums = [1, 5, 6].
- This is valid because nodes 1 and 2 are two edges apart (1 → 0 and 0 → 2), which is at least k.
- The maximum sum is 1 + 5 + 6 = 12.
Example 4:
Input: edges = [[0,1],[0,2]], nums = [1,-5,-6], k = 3
Output: 10
Explanation:

- After inverting the subtree rooted at nodes 0, nums = [-1, 5, 6].
- The maximum sum is (-1) + 5 + 6 = 10.
- Note that we cannot invert nodes 1 and 2 because their distance is 2 < k = 3.
Constraints:
nums.length == nedges.length == n - 12 <= n <= 5 * 10^4edges[i].length == 20 <= edges[i][0], edges[i][1] < n-4 * 10^4 <= nums[i] <= 4 * 10^41 <= k <= 50- It is guaranteed that
edgesforms a tree.
Solution
Approach: Tree DP on Distance to the Nearest Inversion
Here every two inverted nodes must be at least k apart, not only an ancestor and its descendant. Whether a node's value is flipped depends only on the parity of the number of inverted nodes among its ancestors and itself, so we track:
s: the parity (0 or 1) of the inverted strict ancestors, andd: the distance from the node to the nearest inverted node in its own subtree, capped atk(kstands forkor more, or none).
For each node, let res[s][d] be the best sum of its subtree. There are two cases.
- The node is inverted. Its value is flipped once more,
d = 0, and every child's nearest inverted node must be at leastkaway from the node, so each child contributes its best value with distance at leastk - 1from itself. - The node is not inverted. Its children use the same parity
s. We merge the children one by one, keepingm, the distance to the nearest inverted node seen so far. Two parts can be merged whenm + da >= k, wheredais the child's nearest distance as seen from the node (child distance plus one, capped atk), and the new distance ismin(m, da). With suffix maximums this merge takes O(k) instead of O(k2).
The answer is the best res[0][d] at the root. Processing the nodes in reverse BFS order avoids recursion.
Complexity: O(n k) time and O(n k) space.
class Solution:
def subtreeInversionSum(self, edges: List[List[int]], nums: List[int], k: int) -> int:
n = len(nums)
g = [[] for _ in range(n)]
for u, v in edges:
g[u].append(v)
g[v].append(u)
parent = [-1] * n
order = [0]
for u in order:
for v in g[u]:
if v != parent[u]:
parent[v] = u
order.append(v)
NEG = -(10**18)
# res[s][d]: best sum inside u's subtree when an even (s = 0) or odd (s = 1)
# number of ancestors of u are inverted and the nearest inverted node in the
# subtree is d steps from u (d = k means k or more steps, or none).
# cur[u][s][m]: the same while the children of u are merged in one by one,
# with u itself not inverted (m >= 1).
cur = [[[NEG] * (k + 1) for _ in range(2)] for _ in range(n)]
# pick[u][s]: best sum with u inverted, once every child is far enough away
pick = [[0, 0] for _ in range(n)]
for u in range(n):
for s in range(2):
cur[u][s][k] = nums[u] if s == 0 else -nums[u]
pick[u][s] = nums[u] if s == 1 else -nums[u]
for u in reversed(order):
res = [cur[u][s][:] for s in range(2)]
for s in range(2):
res[s][0] = pick[u][s]
cur[u] = None
p = parent[u]
if p < 0:
return max(res[0])
for s in range(2):
# child's best value for each distance da seen from the parent
g1 = [NEG] * (k + 1)
for d in range(k):
da = min(d + 1, k)
g1[da] = max(g1[da], res[s][d])
g1[k] = max(g1[k], res[s][k])
suf_g = g1[:]
for da in range(k - 1, 0, -1):
suf_g[da] = max(suf_g[da], suf_g[da + 1])
c = cur[p][s]
suf_c = c[:]
for m in range(k - 1, 0, -1):
suf_c[m] = max(suf_c[m], suf_c[m + 1])
# two merged parts must be at least k apart: m + da >= k
for x in range(1, k + 1):
best = NEG
t = max(x, k - x) # m = x <= da
if c[x] > NEG and suf_g[t] > NEG:
best = c[x] + suf_g[t]
t = max(x + 1, k - x) # da = x < m
if t <= k and g1[x] > NEG and suf_c[t] > NEG:
best = max(best, g1[x] + suf_c[t])
c[x] = best
pick[p][1 - s] += g1[k]
return 0