Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: Return the maximum path sum between ANY two nodes of a binary tree (a path need not pass through the root; values can be negative).
Problem: Return the maximum path sum between ANY two nodes of a binary tree (a path need not pass through the root; values can be negative).
class T:
def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs):
nodes = [T(x) if x is not None else None for x in xs]
kids = iter(nodes[1:])
for nd in nodes:
if nd:
nd.l = next(kids, None); nd.r = next(kids, None)
return nodes[0]
best = float('-inf')
def gain(nd):
global best
if not nd: return 0
l = max(gain(nd.l), 0); r = max(gain(nd.r), 0)
best = max(best, nd.v + l + r)
return nd.v + max(l, r)
gain(build([2, -1, -3, 4, None, -2, 6]))
print(best)What is printed?- A. 8
- B. 5
- C. 12
- D. 6
Correct answer: A. 8
Left branch gain −1 + 4 = 3; right branch gain −3 + 6 = 3 (the −2 child is clipped to 0). Through the root 2 + 3 + 3 = 8, i.e. the path 4 → −1 → 2 → −3 → 6. A root-to-leaf maximum gives 5, the single best node gives 6, and adding all positive values while ignoring connectivity gives 12.
More Coding Interview Problems questions
- Problem: Count islands in a grid of 1s (land) and 0s where land cells touching even DIAGONALLY belong to the same island. python g =…
- Problem: In an unweighted graph, find the shortest distance from node 0 to node 5 and the NUMBER of distinct shortest paths. python from…
- A Floyd–Warshall implementation writes its loops as for i … for j … for k (k innermost) instead of k outermost, and runs the triple loop…
- Problem: Build a minimum spanning tree with Kruskal's algorithm and report its total weight. python edges =…
- Problem: A CPU runs tasks (letters); identical tasks need at least n idle-or-other slots between them. Find the minimum total time slots…
- Problem: Children stand in a line with ratings; each gets ≥ 1 candy and a child with a higher rating than a NEIGHBOUR must get more than…