Largest Total Value Inside Any Subtree That Is a Valid BST
Last updated: November 29, 2026
Quick Overview
A binary tree of cached shards may be partly corrupted. Among all subtrees that are valid BSTs, return the maximum sum of node values (0 if every valid BST subtree has a negative sum, since the empty tree counts).
0
0
0 solved
A binary tree of cached shards may be partly corrupted. Among all subtrees that are valid BSTs, return the maximum sum of node values (0 if every valid BST subtree has a negative sum, since the empty tree counts).
A Google onsite hard question combining validation with aggregation. The interviewer looks for one post-order pass that returns min, max, sum and validity, instead of re-validating every subtree from scratch.
What the Interviewer Expects
- Return (is_bst, min, max, sum) from each subtree
- Check validity using children's min and max, not just direct children
- Use sentinel bounds for empty subtrees
- Track the global best sum among valid subtrees
- Achieve O(n) instead of O(n^2)
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 size of the largest BST subtree instead of the sum.
- Return the root of that subtree.
- Allow duplicates on the right side.
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: binary tree root with integer values (possibly negative). Output: maximum sum over subtrees that are valid BSTs with strict ordering; empty subtree sum 0 counts, so the answer is at least 0....
High-Level Design
A subtree rooted at x is a valid BST exactly when both children are valid BSTs, max(left) < x.val, and x.val < min(right). Post-order recursion returns four values per subtree: validity, minimum, ...