You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/3000-3099/3068.Find the Maximum Sum of Node Values/README_EN.md
+83-25
Original file line number
Diff line number
Diff line change
@@ -90,7 +90,28 @@ It can be shown that 9 is the maximum achievable sum of values.
90
90
91
91
<!-- solution:start -->
92
92
93
-
### Solution 1
93
+
### Solution 1: Dynamic Programming
94
+
95
+
For any number $x$, its value remains unchanged after being XORed with $k$ an even number of times. Therefore, for any path in a tree, if we perform the operation on all edges in the path, the values of all nodes on the path except the start and end nodes will not change.
96
+
97
+
Additionally, no matter how many operations are performed, there will always be an even number of elements XORed with $k$, and the remaining elements will remain unchanged.
98
+
99
+
Thus, the problem is transformed into: for the array $\textit{nums}$, select an even number of elements to XOR with $k$ to maximize the sum.
100
+
101
+
We can use dynamic programming to solve this problem. Let $f_0$ represent the maximum sum when an even number of elements have been XORed with $k$, and $f_1$ represent the maximum sum when an odd number of elements have been XORed with $k$. The state transition equations are:
102
+
103
+
$$
104
+
\begin{aligned}
105
+
f_0 &= \max(f_0 + x, f_1 + (x \oplus k)) \\
106
+
f_1 &= \max(f_1 + x, f_0 + (x \oplus k))
107
+
\end{aligned}
108
+
$$
109
+
110
+
where $x$ represents the current element's value.
111
+
112
+
We traverse the array $\textit{nums}$ and update $f_0$ and $f_1$ according to the above state transition equations. Finally, we return $f_0$.
113
+
114
+
The time complexity is $O(n)$, where $n$ is the length of the array $\textit{nums}$. The space complexity is $O(1)$.
94
115
95
116
<!-- tabs:start -->
96
117
@@ -100,8 +121,8 @@ It can be shown that 9 is the maximum achievable sum of values.
0 commit comments