Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Find the Maximum Sum of Node Values

XPChallenge Points: 30
levelLevel: Hard

You are given an undirected tree with n nodes labeled from 0 to n - 1.
The tree is represented by an array edges, where each element [u, v] means there is a connection between nodes u and v.

Each node i has an associated non-negative value stored in nums[i].
You are also given a positive integer k.

You may repeatedly apply the following operation:

  • Pick any edge [u, v]

  • Update the values of both nodes by performing:
    nums[u] = nums[u] XOR k
    nums[v] = nums[v] XOR k

Your goal is to maximize the total sum of all node values after performing the operation any number of times (including zero).

Return the highest possible sum that can be achieved.

Example 1:

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

Output: 15

Explanation:

- Apply XOR on edge [1,2]: nums becomes [4, 1 XOR 5 = 4, 6 XOR 5 = 3] → [4,4,3] - Apply XOR on edge [0,1]: nums becomes [4 XOR 5 = 1, 4 XOR 5 = 1, 3] → [1,1,3] Sum = 1 + 1 + 3 = 5 - Instead, applying XOR once on each edge gives better: Final nums = [9, 4, 6] Sum = 19 (maximum)

Example 2:

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

Output: 31

Example 3:

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

Output: 14

Explanation:

Applying XOR on edges twice flips values beneficially.

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result