Watch 2 video solutions for Subtree Inversion Sum, a hard level problem involving Array, Dynamic Programming, Tree. This walkthrough by Programming Live with Larry has 235 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
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 and b such that one is an ancestor of the other (i.e., if LCA(a, b) = a or LCA(a, b) = b), then the distance (the number of edges on the unique path between them) must be at least k.
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:

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:

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 * 104edges.length == n - 1edges[i] = [ui, vi]0 <= ui, vi < nnums.length == n-5 * 104 <= nums[i] <= 5 * 1041 <= k <= 50edges represents a valid tree.Problem Overview: You are given a tree where each node contains a value. For every node, consider the values inside its subtree and compute the number of inversion pairs (i, j) where i appears before j but value[i] > value[j]. The goal is to efficiently compute the inversion contribution across all subtrees.
Approach 1: Brute Force Subtree Extraction + Merge Sort (O(n^2 log n) time, O(n) space)
Run a depth-first search from every node and collect all values belonging to its subtree into an array. Once the array is built, compute inversion count using a merge-sort based inversion counter. Merge sort counts cross inversions during the merge step in O(k log k) for a subtree of size k. Repeating this for all nodes leads to roughly O(n^2 log n) time in the worst case because many subtree arrays overlap heavily.
Approach 2: Euler Tour + Fenwick Tree (O(n log^2 n) time, O(n) space)
Flatten the tree using a DFS Euler tour so every subtree becomes a contiguous segment in an array. With this representation, subtree queries turn into range queries. For each subtree segment, iterate through values and use a Fenwick Tree (Binary Indexed Tree) to count how many previously seen elements are greater than the current value. Coordinate compression keeps Fenwick indices small. This approach reduces repeated traversal but still rebuilds the inversion structure for many ranges, resulting in O(n log^2 n) time.
Approach 3: DSU on Tree (Small-to-Large) with Fenwick Tree (O(n log n) time, O(n) space)
The optimal strategy processes the tree bottom-up using the "small-to-large" merging technique (commonly called DSU on Tree). During a tree DFS, each node maintains a frequency structure (Fenwick Tree or ordered map) representing values in its subtree. When combining children, always merge the smaller structure into the larger one. While inserting values, query how many existing values are greater to accumulate inversion counts. Each element moves at most O(log n) times across merges, giving an overall O(n log n) complexity. This technique avoids recomputing subtree data and is standard for heavy subtree aggregation problems that combine dynamic programming with DFS.
Recommended for interviews: Start by describing the brute force subtree extraction to demonstrate understanding of inversion counting. Interviewers typically expect the optimized DSU-on-tree or Fenwick-based aggregation because it avoids recomputation and runs in O(n log n). Recognizing the Euler tour transformation and small-to-large merging shows strong tree and DFS problem-solving skills.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Subtree + Merge Sort | O(n^2 log n) | O(n) | Small input sizes or when demonstrating inversion counting basics |
| Euler Tour + Fenwick Tree | O(n log^2 n) | O(n) | When subtree ranges can be flattened and handled with range-based queries |
| DSU on Tree (Small-to-Large) + Fenwick | O(n log n) | O(n) | Optimal general solution for large trees and interview settings |