Subtree Inversion Sum II - Solution & Explanation
Problem Statement
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.
-
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 → 0and0 → 2), which is at leastk. - 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 * 104edges[i].length == 20 <= edges[i][0], edges[i][1] < n-4 * 104 <= nums[i] <= 4 * 1041 <= k <= 50- It is guaranteed that
edgesforms a tree.
Approach Overview
Problem Overview: You are given a tree where each node has a value. For every node, consider the values inside its subtree and count inversion pairs (i, j) where i appears before j but value[i] > value[j]. The task is to efficiently compute the inversion contribution across all subtrees without recomputing from scratch for each node.
Approach 1: Recompute Inversions Per Subtree (Brute Force) (O(n^2 log n) time, O(n) space)
Traverse the tree with DFS. For each node, collect all values from its subtree into an array. Run a classic inversion counting algorithm using merge sort on that array. Merge sort counts inversions in O(k log k) for a subtree of size k. Since many subtrees overlap and nodes may be processed repeatedly, the total runtime grows toward O(n^2 log n). This method is straightforward and useful for validating correctness on small inputs but does not scale to large trees.
Approach 2: DFS + Small-to-Large Set Merging (DSU on Tree) (O(n log n) time, O(n) space)
Process the tree using postorder DFS. Each node maintains a balanced structure (such as a multiset or Fenwick-friendly ordered container) storing values from its subtree. While returning from recursion, merge child containers into the largest one using the small-to-large technique. When inserting elements from the smaller container, query how many existing values are greater to count new inversion pairs. Because each element moves containers only logarithmically many times, the total complexity becomes O(n log n). This pattern is commonly called DSU on tree and appears frequently in advanced tree problems.
Approach 3: Euler Tour + Fenwick Tree (O(n log n) time, O(n) space)
Flatten the tree using an Euler tour so every subtree becomes a contiguous range in an array. After coordinate-compressing values, process nodes while maintaining a Fenwick Tree or Binary Indexed Tree. As nodes enter the structure, query the number of previously inserted values greater than the current one to accumulate inversion counts. Range boundaries from the Euler tour allow subtree queries to be handled efficiently. This approach replaces explicit set merging with prefix-sum queries and updates.
Recommended for interviews: Interviewers usually expect the small-to-large merging (DSU on tree) approach or an Euler tour combined with a Fenwick Tree. The brute-force solution demonstrates understanding of inversion counting with merge sort, but the optimized O(n log n) solution shows you can combine DFS, subtree processing, and ordered data structures to eliminate repeated work.
Solutions for this problem are being prepared.
Try solving it yourselfDetailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Recompute inversions per subtree (merge sort) | O(n^2 log n) | O(n) | Conceptual baseline or small constraints |
| DFS with small-to-large merging (DSU on tree) | O(n log n) | O(n) | General optimal solution for subtree aggregation |
| Euler tour + Fenwick Tree | O(n log n) | O(n) | When subtree ranges can be flattened into array intervals |
Frequently Asked Questions
Is Subtree Inversion Sum II easy or hard?
Subtree Inversion Sum II Python/Java solution
How to solve Subtree Inversion Sum II in O(n log n)?
What is the best approach for Subtree Inversion Sum II?
Is Subtree Inversion Sum II asked at Google/Amazon/Meta?
What data structure is used in Subtree Inversion Sum II?
What is the time complexity of Subtree Inversion Sum II?
Ready to solve this problem?
Practice Subtree Inversion Sum II with our built-in code editor and test cases.
Practice on FleetCodeProblem Info
Table of Contents
Practice this problem
Open in Editor