Highest-Value Path Between Any Two Nodes With Negative Weights
Last updated: November 29, 2026
Quick Overview
Each node in a binary tree has a signed value (gain or loss). A path is any sequence of nodes connected by parent-child edges, used at most once each, with at least one node. Return the maximum path sum.
0
0
0 solved
Each node in a binary tree has a signed value (gain or loss). A path is any sequence of nodes connected by parent-child edges, used at most once each, with at least one node. Return the maximum path sum.
A frequent Google onsite hard question. Interviewers want a clear separation between the value a subtree can offer upward (one branch only) and the best path that bends at a node (both branches), plus correct handling of all-negative trees.
What the Interviewer Expects
- Distinguish the upward single-branch gain from the bending path through a node
- Clamp negative branch gains to zero
- Update a global best at every node
- Handle an all-negative tree by not allowing an empty path
- Run in O(n) with one post-order pass
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Return the path itself, not only the sum.
- What if the path must start and end at leaves?
- Make it iterative for a tree with a million nodes in a chain.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: root with integer values, at least one node. Output: maximum sum over all non-empty paths, where a path may bend at most once (at its highest node) and need not pass through the root....
High-Level Design
For each node compute gain(node): the best sum of a downward path starting at this node and going into at most one child. That is val + max(0, gain(left), gain(right)): a branch with negative gain...