#3068
Find the Maximum Sum of Node Values
HardArrayDynamic ProgrammingGreedyBit ManipulationTreeSortingDynamic ProgrammingTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses dynamic programming to efficiently compute the maximum sum by considering the effect of each edge on the subtree sums. By leveraging the tree structure, we can avoid redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Construct the tree from the edges.
- 2Step 2: Use DFS to calculate the maximum sum for each subtree, considering the XOR operation with k.
- 3Step 3: For each node, calculate the maximum sum with and without the XOR operation, and propagate the results up the tree.
solution.py21 lines
1# Full working Python code
2from collections import defaultdict
3
4def max_sum_optimal(nums, k, edges):
5 tree = defaultdict(list)
6 for u, v in edges:
7 tree[u].append(v)
8 tree[v].append(u)
9
10 def dfs(node, parent):
11 total = nums[node]
12 total_with_xor = nums[node] ^ k
13 subtree_sum = 0
14 for neighbor in tree[node]:
15 if neighbor == parent:
16 continue
17 child_sum = dfs(neighbor, node)
18 subtree_sum += child_sum
19 return max(total + subtree_sum, total_with_xor + subtree_sum)
20
21 return dfs(0, -1)ℹ
Complexity note: The complexity is linear because we traverse each node once in the DFS, and the space complexity is also linear due to the storage of the tree structure.
- 1XOR operation can change the values significantly, and careful selection of edges can maximize the sum.
- 2The tree structure allows for efficient traversal and computation of subtree sums.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.