root of a binary tree, return the maximum path sum of any non-empty path.
Two key insights:
Negative gains are discarded — if a subtree has a negative contribution, we simply don't include it (clamp to 0).
The path through a node uses both left and right (L + node + R) — this is the candidate for global max. But we can only return one direction to the parent (a path can't fork). The global variable captures the best full path independently of what's returned upward.
Trying every pair of end points and summing the path between them is far too slow. Instead, each node can report the best downward path it can offer to its parent.
Define the gain of a node as its value plus the better of its two downward gains. A negative gain only hurts, so treat it as 0. At each node, the best path that bends here is its value plus the left gain plus the right gain. Update a global best with that bending path. But return only one side to the parent, because a path cannot split in two.
Record the bending path, but return a single branch. Clamp negative gains to 0.
Run the animation above on your own input, or watch the 2:10 video explanation of Binary Tree Maximum Path Sum with a dry run and Java code.