Skip to content

Practice Subtree Inversion Sum

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Hard#3544
LeetCode Problem

Subtree Inversion Sum

Problem Statement

Given the tree rooted at 0, node values nums, and k, select a subset of nodes to invert. Inverting a node multiplies every value in its subtree by -1, so overlapping inversions apply cumulatively. Any two selected nodes that are ancestor and descendant must be at least k edges apart; nodes in separate branches have no such restriction. Return the maximum achievable sum of all node values.

Source: Subtree Inversion Sum on LeetCode. Use the original task for its coding environment and submissions.

Examples

# 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

# Example 2

Input
edges = [[0,1],[1,2],[2,3],[3,4]], nums = [-1,3,-2,4,-5], k = 2
Output
9

# Example 3

Input
edges = [[0,1],[0,2]], nums = [0,-1,-2], k = 3
Output
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.

Related LeetCode Problems

Practice more problems similar to Subtree Inversion Sum.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.