My first instinct was to just do a DFS and track the running max, which is the right direction, but I kept second-guessing whether the path had to go through the root.
Use a post-order DFS that returns the maximum gain from each subtree while updating a global maximum path sum. At each node, compute the best path through the node as node.val + max(0, leftGain) + max(0, rightGain), and return node.val + max(0, max(leftGain, rightGain)) to the parent.
Pro tip: Clarify that a path can start and end at any node, so you must consider paths that pass through a node and connect its left and right subtrees. Also, mention that negative values are handled by taking max(0, gain) to avoid including them.
Confirm that a path can start and end at any node, may not pass through the root, and that a single node is a valid path. Ask about constraints (e.g., node values can be negative).
Define a helper function that returns the maximum gain from a subtree rooted at a given node, where gain is the maximum sum of a path starting at that node and going down to any node in its subtree.
For each node, recursively compute left and right gains. Ignore negative gains by taking max(0, gain). Update the global maximum with node.val + leftGain + rightGain.
Return node.val + max(leftGain, rightGain) to the parent, since a path cannot branch when going up.
State that the algorithm visits each node once, so time complexity is O(n) and space complexity is O(h) for recursion stack, where h is the tree height.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.