Magicsheet logo

Find the Maximum Sum of Node Values

Hard
73.2%
Updated 6/1/2025

Find the Maximum Sum of Node Values

What is this problem about?

The Find the Maximum Sum of Node Values interview question gives you a tree with nn nodes, each having an integer value. You are also given an integer kk. You can perform an operation on any edge (u,v)(u, v): replace val[u]val[u] with val[u]kval[u] \oplus k and val[v]val[v] with val[v]kval[v] \oplus k. You can perform this operation any number of times. Your goal is to find the maximum possible sum of all node values in the tree.

Why is this asked in interviews?

This "Hard" problem is popular at Google, Meta, and BlackRock because it tests your ability to identify invariants in graph operations. The key observation is that because we can perform the operation along any path, we can essentially pick any two nodes in the tree and XOR both of them with kk. This reduces a tree problem to a simple array-parity problem. It evaluation your understanding of Bit Manipulation and Greedy interview patterns.

Algorithmic pattern used

This problem uses Greedy logic with Parity.

  1. For each node, there are two possible values: valval and valkval \oplus k.
  2. The operation always changes the parity of the number of nodes XORed with kk. Since we change two nodes at a time, the total number of nodes XORed with kk must be even.
  3. Calculate the "gain" for each node: gain=(valk)valgain = (val \oplus k) - val.
  4. Sort nodes by their gains in descending order.
  5. Iterate through the sorted gains in pairs. If the sum of a pair of gains is positive, add it to the initial sum of the tree.

Example explanation

nums = [1, 2, 1], k=3k = 3.

  1. Original sum: 1+2+1=41+2+1 = 4.
  2. Possible values (val3val \oplus 3):
    • 1 XOR 3 = 2. Gain = +1.
    • 2 XOR 3 = 1. Gain = -1.
    • 1 XOR 3 = 2. Gain = +1.
  3. Sorted Gains: [+1, +1, -1].
  4. Pair 1: (+1, +1). Sum = 2 (Positive). Add to total. Result: 4+2=64 + 2 = 6. (Nodes 0 and 2 were XORed with 3).

Common mistakes candidates make

  • Tree Traversal: Trying to use complex DFS or DP on the tree structure, which is unnecessary once you realize you can XOR any pair.
  • Ignoring Parity: Forgetting that you must XOR nodes in pairs. You can't just take all nodes where the gain is positive.
  • Sorting error: Not correctly calculating the gain (it can be negative).

Interview preparation tip

Whenever a problem allows operations on edges that affect both endpoints, check if the operation can be "chained" to affect any two nodes in the graph. This often simplifies graph problems into basic parity or sum optimization problems.

Similar Questions