Find the Most Profitable Path Anywhere in a Revenue Tree
Last updated: November 29, 2026
Quick Overview
Each node of a binary tree holds the profit (possibly negative) of a business unit. A path is any sequence of connected nodes with no node repeated, and it need not pass through the root. Return the largest path sum.
Amazon
November 29, 20260
0
0 solved
Each node of a binary tree holds the profit (possibly negative) of a business unit. A path is any sequence of connected nodes with no node repeated, and it need not pass through the root. Return the largest path sum.
A Hard onsite problem Amazon interviewers like because it separates candidates who understand what a recursive call should return from those who mix it up with the global answer. Expect to be asked to justify every max in the recurrence.
What the Interviewer Expects
- Separate the value returned to the parent (a single downward arm) from the best path through the node (both arms)
- Clamp negative child contributions to zero
- Initialize the answer to negative infinity so all-negative trees work
- Trace a small example aloud to prove the recurrence
- State O(n) time and O(h) stack
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
- How would you also return the endpoints of the best path?
- What if the path had to contain at least one leaf at each end?
- How would you handle a tree too deep for recursion?
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 of a non-empty binary tree with integer values. Output: the maximum sum over all non-empty paths, where a path may bend once at its highest node. If every value is negative, the answer is ...
High-Level Design
Post-order DFS. For each node compute gain(node): the best sum of a path that starts at this node and goes down one side, which is what a parent can extend. Gains below zero are dropped (take 0 inst...