Ezvor

3949. Subtree Inversion Sum II

HardArray Preparing judge… LeetCode
ArrayDynamic ProgrammingTreeDepth-First Search

Hints

Hint 1
Root the tree at 0. Do not track only inverted ancestors; the constraint is between any two inverted nodes, including nodes in different child subtrees.
Hint 2
Use DP by distance. Let mx[u][d] and mn[u][d] be the maximum/minimum possible subtree sum of u, assuming every inverted node inside this subtree is at distance at least d from u. Cap distances at k.
Hint 3
When merging child subtrees, if one inverted node is in one child at distance a from that child, and another is in a different child at distance b, their distance through u is a + b + 2, so it must be at least k.
Hint 4
Store both max and min because inverting u negates the whole subtree. So the best value after inverting u comes from negating the minimum compatible child sum, and the worst comes from negating the maximum compatible child sum.