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).

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

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
binary search tree
post-order traversal
tree dynamic programming
validation
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 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 Problems
Sample 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, ...


Submit Your Answer
Markdown supported