Subtree Inversion Sum Problem
Description
LeetCode Problem 3544.
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.
- Specifically, if you invert two nodes
aandbsuch that one is an ancestor of the other (i.e., ifLCA(a, b) = aorLCA(a, b) = b), then 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],[1,3],[1,4],[2,5],[2,6]], nums = [4,-8,-6,3,7,-2,5], k = 2
Output: 27
Explanation:

- Apply inversion operations at nodes 0, 3, 4 and 6.
- The final nums array is [-4, 8, 6, 3, 7, 2, 5], and the total sum is 27.
Example 2:
Input: edges = [[0,1],[1,2],[2,3],[3,4]], nums = [-1,3,-2,4,-5], k = 2
Output: 9
Explanation:

- Apply the inversion operation at node 4.
- The final nums array becomes [-1, 3, -2, 4, 5], and the total sum is 9.
Example 3:
Input: edges = [[0,1],[0,2]], nums = [0,-1,-2], k = 3
Output: 3
Explanation:
Apply inversion operations at nodes 1 and 2.
Constraints:
2 <= n <= 5 * 10^4edges.length == n - 1edges[i] = [u_i, v_i]0 <= u_i, v_i < nnums.length == n-5 * 10^4 <= nums[i] <= 5 * 10^41 <= k <= 50- The input is generated such that
edgesrepresents a valid tree.
Solution
Approach: Tree DP with Distance to the Last Inversion
Whether we may invert a node depends only on its distance to the nearest inverted ancestor (inverted ancestors further up are even farther away). So describe the situation of node u by j, the distance to that ancestor, capped at k; j = k means "far enough", which also covers having no inverted ancestor.
Because inverting a subtree flips the sign of everything below it, keep two values for each state: mx[u][j], the largest and mn[u][j], the smallest total of u's subtree.
- Do not invert
u: its value isnums[u], plus the children in statemin(j + 1, k):mx = nums[u] + sum(mx[child][j']), and likewise formn. - Invert
u(only ifj == k): its value becomes-nums[u], every child is at distance1, and the whole child subtree is negated, so the largest total uses the children's smallest and the other way round:mx = -nums[u] - sum(mn[child][1]),mn = -nums[u] - sum(mx[child][1]).
Keep the better choice for each of mx and mn. Process nodes in reverse BFS order to avoid deep recursion. The answer is mx[0][k].
Complexity: O(n * k) time and O(n * k) extra 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 a, b in edges:
g[a].append(b)
g[b].append(a)
parent = [-1] * n
order = [0]
for u in order:
for v in g[u]:
if v != parent[u]:
parent[v] = u
order.append(v)
# mx[u][j] / mn[u][j]: best / worst subtree sum of u when the nearest inverted ancestor
# is j edges above u (j = k means "far enough", also used when there is none)
mx = [[0] * (k + 1) for _ in range(n)]
mn = [[0] * (k + 1) for _ in range(n)]
for u in reversed(order):
kids = [v for v in g[u] if v != parent[u]]
# sums over the children for the two cases: u not inverted, u inverted
s_keep_mx = [0] * (k + 1)
s_keep_mn = [0] * (k + 1)
inv_mx = inv_mn = 0
for v in kids:
inv_mx -= mn[v][1]
inv_mn -= mx[v][1]
for j in range(1, k + 1):
nj = min(j + 1, k)
a = b = 0
for v in kids:
a += mx[v][nj]
b += mn[v][nj]
s_keep_mx[j] = a
s_keep_mn[j] = b
for j in range(1, k + 1):
hi = nums[u] + s_keep_mx[j]
lo = nums[u] + s_keep_mn[j]
if j == k:
hi = max(hi, -nums[u] + inv_mx)
lo = min(lo, -nums[u] + inv_mn)
mx[u][j] = hi
mn[u][j] = lo
return mx[0][k]