LeetCode in Kotlin

3068. Find the Maximum Sum of Node Values

Hard

There exists an undirected tree with n nodes numbered 0 to n - 1. You are given a 0-indexed 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the tree. You are also given a positive integer k, and a 0-indexed array of non-negative integers nums of length n, where nums[i] represents the value of the node numbered i.

Alice wants the sum of values of tree nodes to be maximum, for which Alice can perform the following operation any number of times (including zero) on the tree:

Return the maximum possible sum of the values Alice can achieve by performing the operation any number of times.

Example 1:

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

Output: 6

Explanation: Alice can achieve the maximum sum of 6 using a single operation:

The total sum of values is 2 + 2 + 2 = 6.

It can be shown that 6 is the maximum achievable sum of values.

Example 2:

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

Output: 9

Explanation: Alice can achieve the maximum sum of 9 using a single operation:

The total sum of values is 5 + 4 = 9.

It can be shown that 9 is the maximum achievable sum of values.

Example 3:

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

Output: 42

Explanation: The maximum achievable sum is 42 which can be achieved by Alice performing no operations.

Constraints:

Solution

import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min

@Suppress("UNUSED_PARAMETER")
class Solution {
    fun maximumValueSum(nums: IntArray, k: Int, edges: Array<IntArray>): Long {
        var res: Long = 0
        var d = 1 shl 30
        var c = 0
        for (a in nums) {
            val b = a xor k
            res += max(a, b)
            c = c xor if (a < b) 1 else 0
            d = min(d, abs((a - b)))
        }
        return res - d * c
    }
}