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: 6
💡 Note: Calculate XOR benefits: node 0: (1^3)-1=1, node 1: (2^3)-2=-1, node 2: (1^3)-1=1. Sort benefits: [1,1,-1]. Since we need even number of XORed nodes, we can select 0 nodes (sum=4) or 2 nodes with highest benefits (sum=4+1+1=6). Maximum is 6.
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
Maximum Sum of Node Values INPUT 0 1 2 nums[0]=1 nums[1]=2 nums[2]=1 nums = [1, 2, 1] k = 3 edges = [[0,1],[0,2]] Initial sum: 1+2+1 = 4 ALGORITHM STEPS 1 Calculate Benefits benefit[i] = (nums[i] XOR k) - nums[i] Node 0: (1 XOR 3) - 1 = 2 - 1 = 1 Node 1: (2 XOR 3) - 2 = 1 - 2 = -1 Node 2: (1 XOR 3) - 1 = 2 - 1 = 1 2 Sort by Benefit Sort descending: [1, 1, -1] 3 Pair Selection Must XOR in pairs (even count) Pick nodes 0 and 2 (both +1) Total benefit: 1 + 1 = 2 4 Calculate Result Original sum + total benefit 4 + 2 + 2 = 8 FINAL RESULT 0 2 1 2 2 2 1 XOR 3 = 2 1 XOR 3 = 2 (unchanged) Output 8 New values: [2, 2, 2] Sum = 2 + 2 + 2 = 8 OK - Maximum achieved! Key Insight: XOR operation on an edge affects exactly 2 nodes. Path between any two nodes has odd edges, so we can XOR any pair of nodes. Greedy: pick pairs with positive combined benefit (even count). TutorialsPoint - Find the Maximum Sum of Node Values | Greedy Approach
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