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.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

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
binary trees
post-order traversal
tree dynamic programming
maximum path sum
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample 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...


Submit Your Answer
Markdown supported