Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the maximum sum of any path in a tree (a path goes between any two nodes, need not pass through the root, values may be negative). Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
Problem: Find the maximum sum of any path in a tree (a path goes between any two nodes, need not pass through the root, values may be negative). Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
class T:
def __init__(self, v, l=None, r=None):
self.v, self.l, self.r = v, l, r
def build(xs, i=0):
if i >= len(xs) or xs[i] is None: return None
return T(xs[i], build(xs, 2*i+1), build(xs, 2*i+2))
def max_path(root):
best = float('-inf')
def gain(t):
nonlocal best
if not t: return 0
l, r = max(gain(t.l), 0), max(gain(t.r), 0)
best = max(best, t.v + l + r)
return t.v + max(l, r)
gain(root)
return best
print(max_path(build([-10, 9, 20, None, None, 15, 7])), max_path(build([-3])))What is printed?- A. 42 0
- B. 34 -3
- C. 35 -3
- D. 42 -3
Correct answer: D. 42 -3
Each node reports the best downward gain (negative branches clipped to 0) and updates the answer with the path that bends at it. 15 → 20 → 7 = 42 beats anything through −10. A single negative node must still be returned (−3), so best starts at −∞, not 0. O(n).
More Coding Interview Problems questions
- Problem: Count root-to-leaf paths whose values sum to a target. Trees are built by build(xs): a level-order list where index i has…
- Problem: Count downward paths (starting anywhere, ending anywhere below) that sum to k, using prefix sums on the root-to-node path. Trees…
- Problem: Serialize a tree in preorder with '#' for missing children, then count the nodes from the string alone. python class T: def…
- Problem: Rebuild a tree from its preorder and inorder sequences (distinct values) and print its postorder. python def post(pre, ino): if…
- Problem: Check whether a tree is height-balanced (every node's subtree heights differ by at most 1). Trees are built by build(xs): a…
- Problem: Return the zigzag level order (left→right, then right→left, alternating). Trees are built by build(xs): a level-order list where…