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.
The key insight is that XOR operations on tree edges create parity constraints - we need an even number of node transformations. The optimal approach calculates XOR benefits for each node independently, sorts them, and selects the maximum even-sized subset. Time: O(n log n), Space: O(n)
Common Approaches
✓
Memoization
⏱️ Time: N/A
Space: N/A
Sort First
⏱️ Time: N/A
Space: N/A
Brute Force - Try All Combinations
⏱️ Time: O(2^(n²))
Space: O(n)
Generate all possible states by trying every combination of applying XOR operations to each edge. Since each edge can be used 0, 1, 2, or more times, we need to consider the effect of multiple operations.
Greedy - Maximize Individual Benefits
⏱️ Time: O(n log n)
Space: O(n)
For each node, calculate the benefit of applying XOR operation (nums[i] ^ k - nums[i]). Sort nodes by benefit and greedily apply operations that give positive benefit, considering parity constraints.
Optimal - XOR Parity Analysis
⏱️ Time: O(n log n)
Space: O(n)
Key insight: XOR operations on edges can be viewed as flipping node states. The tree structure means we need an even number of flipped nodes. We can calculate the optimal solution by considering all nodes independently with parity constraint.
Algorithm Steps — Algorithm Steps
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 1000
static int nums[MAX_SIZE];
static long long benefits[MAX_SIZE];
static int edges[MAX_SIZE][2];
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
if (strcmp(str, "[]") == 0 || strcmp(str, "[]\n") == 0) return;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
char* endptr;
arr[(*size)++] = (int)strtol(p, &endptr, 10);
p = endptr;
}
}
void parseEdges(const char* str, int edges[][2], int* edgeCount) {
*edgeCount = 0;
if (strcmp(str, "[]") == 0 || strcmp(str, "[]\n") == 0) return;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
if (*p == '[') {
p++;
char* endptr;
edges[*edgeCount][0] = (int)strtol(p, &endptr, 10);
p = endptr;
while (*p == ' ' || *p == ',') p++;
edges[*edgeCount][1] = (int)strtol(p, &endptr, 10);
p = endptr;
(*edgeCount)++;
while (*p && *p != ']') p++;
if (*p == ']') p++;
} else {
p++;
}
while (*p == ' ' || *p == ',') p++;
}
}
int compareLongLong(const void* a, const void* b) {
long long diff = *(long long*)b - *(long long*)a;
return (diff > 0) ? 1 : (diff < 0) ? -1 : 0;
}
long long solution(int* nums, int n, int k, int edges[][2], int edgeCount) {
if (n == 1) {
long long original = (long long)nums[0];
long long xored = (long long)(nums[0] ^ k);
return (original > xored) ? original : xored;
}
long long originalSum = 0;
for (int i = 0; i < n; i++) {
originalSum += nums[i];
benefits[i] = (long long)(nums[i] ^ k) - nums[i];
}
qsort(benefits, n, sizeof(long long), compareLongLong);
long long maxSum = originalSum;
long long currentBonus = 0;
for (int count = 2; count <= n; count += 2) {
currentBonus += benefits[count-2] + benefits[count-1];
long long candidate = originalSum + currentBonus;
maxSum = (maxSum > candidate) ? maxSum : candidate;
}
return maxSum;
}
int main() {
char numsStr[MAX_SIZE];
char kStr[MAX_SIZE];
char edgesStr[MAX_SIZE];
fgets(numsStr, MAX_SIZE, stdin);
fgets(kStr, MAX_SIZE, stdin);
fgets(edgesStr, MAX_SIZE, stdin);
int n;
parseArray(numsStr, nums, &n);
int k = atoi(kStr);
int edgeCount;
parseEdges(edgesStr, edges, &edgeCount);
printf("%lld\n", solution(nums, n, k, edges, edgeCount));
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
⚡ Linearithmic
Space Complexity
n
2n
⚡ Linearithmic Space
23.0K Views
MediumFrequency
~35 minAvg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.