Largest Revenue Subtree That Forms a Valid Search Tree

Last updated: November 29, 2026

Quick Overview

A binary tree holds revenue values that are only partly ordered. Return the maximum sum of node values over all subtrees that are valid binary search trees (an empty subtree has sum 0).

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

0

0

0 solved


A binary tree holds revenue values that are only partly ordered. Return the maximum sum of node values over all subtrees that are valid binary search trees (an empty subtree has sum 0).

An Amazon onsite Hard that combines BST validation with tree DP. Interviewers watch for a single post-order pass that returns enough information from each child, rather than re-validating every subtree from scratch.

What the Interviewer Expects
  • Reject the O(n^2) approach that validates each subtree separately
  • Return (is_bst, min, max, sum) from each child in post-order
  • Use infinities for empty subtrees so leaf checks work
  • Update a global best only for valid BST subtrees
  • Explain why negative sums mean the empty subtree (0) can win
Key Topics to Cover
BST
tree DP
post-order traversal
binary trees
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
  • How would you return the size of the largest BST subtree instead of its sum?
  • How would you make this iterative?
  • What if duplicates were allowed on the left side?
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 of a binary tree of integers. Output: the largest sum of any subtree (a node plus all its descendants) that is a valid BST with strictly increasing inorder values, or 0 if all such sums ar...

High-Level Design

Post-order DFS returns four values for each subtree: whether it is a BST, its minimum, its maximum, and its sum. An empty subtree returns (True, +inf, -inf, 0), which makes any parent comparison pass....


Submit Your Answer
Markdown supported