Binary Tree Maximum Path Sum
Find the maximum sum over any path (any node to any node, no revisits).
Open on LeetCode ↗Intuition
Like diameter, but weighted and with negatives. Each node answers two different questions: 'best downward path starting here' (what the parent can use — one branch only) and 'best path bending here' (left gain + node + right gain — a candidate answer). Negative branches contribute 0: better to not extend.
Approach
Gain = usable path
gain(node) = node.val + max(gain(left), gain(right), both clamped at 0). A parent can extend through only one child.
Bend = candidate
At each node, leftGain + node.val + rightGain uses both branches — legal as a full path, illegal to pass upward. Track its max globally.
Clamp negatives to zero
max(gain, 0) implements 'drop a branch that hurts' — the crux with negative values.
Solution & live demo
Edge cases
Clamps make gains 0, but the bend at each single node still records node.val — the answer is the largest (least negative) node.
Bend = its value.