Problem
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] = [ui, vi]
indicates an edge between nodes ui
and vi
.
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
a
andb
such that one is an ancestor of the other (i.e., ifLCA(a, b) = a
orLCA(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.
Examples
Example 1
|
|
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
|
|
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
|
|
Constraints
2 <= n <= 5 * 10^4
edges.length == n - 1
edges[i] = [ui, vi]
0 <= ui, vi < n
nums.length == n
-5 * 10^4 <= nums[i] <= 5 * 10^4
1 <= k <= 50
- The input is generated such that
edges
represents a valid tree.
Solution
Method 1 – DFS with Bitmask Dynamic Programming
Intuition
We need to maximize the sum of the nums array after performing at most k subtree inversions. Each inversion flips the sign of all values in a subtree. The optimal solution involves choosing up to k subtrees such that their inversions do not overlap and the total sum is maximized. We use DFS to compute subtree sums and DP with bitmasking to track inversion choices efficiently.
Approach
- Build the tree from the edges.
- Use DFS to compute the sum of each subtree and store the children for each node.
- Use DP with memoization: dp[node][inversions_left] gives the max sum for the subtree rooted at node with a given number of inversions left.
- For each node, try all possible ways to distribute inversions among its children and itself.
- If we invert the current node’s subtree, subtract twice its sum from the total.
- Return the maximum sum after at most k inversions.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n * k^2)
– Each node and inversion count is considered, with DP and DFS. - 🧺 Space complexity:
O(n * k)
– For DP table and subtree sums.