Class Solution

  • All Implemented Interfaces:

    
    public final class Solution
    
                        

    3544 - Subtree Inversion Sum.

    Hard

    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 <code>edgesi = u<sub>i</sub>, v<sub>i</sub></code> indicates an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.

    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:

    • Distance Constraint on Inversions:

    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:

    • 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:

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

    Output: 9

    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:

    Input: edges = [0,1,0,2], nums = 0,-1,-2, k = 3

    Output: 3

    Explanation:

    Apply inversion operations at nodes 1 and 2.

    Constraints:

    • <code>2 <= n <= 5 * 10<sup>4</sup></code>

    • edges.length == n - 1

    • <code>edgesi = u<sub>i</sub>, v<sub>i</sub></code>

    • <code>0 <= u<sub>i</sub>, v<sub>i</sub>< n</code>

    • nums.length == n

    • <code>-5 * 10<sup>4</sup><= numsi<= 5 * 10<sup>4</sup></code>

    • 1 &lt;= k &lt;= 50

    • The input is generated such that edges represents a valid tree.

    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
    • Field Summary

      Fields 
      Modifier and Type Field Description
    • Constructor Summary

      Constructors 
      Constructor Description
      Solution()
    • Enum Constant Summary

      Enum Constants 
      Enum Constant Description
    • Method Summary

      Modifier and Type Method Description
      final Long subtreeInversionSum(Array<IntArray> edges, IntArray nums, Integer k)
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait