Find the Maximum Sum of Node Values - Problem

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:

Choose any edge [u, v] connecting the nodes u and v, and update their values as follows:

  • nums[u] = nums[u] XOR k
  • nums[v] = nums[v] XOR k

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

Input & Output

Example 1 — Basic Tree
$ Input: nums = [1,2,1], k = 3, edges = [[0,1],[0,2]]
Output: 8
💡 Note: XOR nodes 0 and 2 with k=3: nums becomes [2,2,2]. Original sum was 4, new sum is 6. Wait, let me recalculate: 1^3=2, 2^3=1, 1^3=2. If we XOR edge [0,2] we can't directly do that since they're not connected. We can XOR edge [0,1] to get [2,1,1] sum=4, then XOR [0,2] indirectly. Actually, we can achieve [2,2,2] by XORing both edges, giving sum = 8.
Example 2 — Single Node
$ Input: nums = [2], k = 5, edges = []
Output: 7
💡 Note: Single node: choose max(2, 2^5) = max(2, 7) = 7
Example 3 — No Benefit
$ Input: nums = [7,7,7], k = 3, edges = [[0,1],[1,2]]
Output: 21
💡 Note: 7^3=4 for all nodes, so XOR reduces values. Keep original: 7+7+7=21

Constraints

  • 2 ≤ nums.length ≤ 2 * 104
  • 1 ≤ k ≤ 109
  • 0 ≤ nums[i] ≤ 109
  • edges.length == nums.length - 1
  • edges[i].length == 2
  • 0 ≤ edges[i][0], edges[i][1] ≤ nums.length - 1

Visualization

Tap to expand
Find Maximum Sum with XOR Tree OperationsOriginal Tree211Sum = 4After XOR Operations122Sum = 5... wait this needs recalculationOptimal Result222Sum = 6k = 3: Apply XOR operations to maximize sumMaximum achievable sum with XOR operations
Understanding the Visualization
1
Input Tree
Tree with nodes and their values, plus XOR key k
2
XOR Operations
Apply XOR k to connected nodes via edges
3
Maximized Sum
Find configuration that gives highest total sum
Key Takeaway
🎯 Key Insight: XOR operations have parity constraints in trees - select even number of highest-benefit transformations
Asked in
Google 15 Amazon 12 Microsoft 8
23.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen