Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Rob houses arranged as a tree (node 0 is the root; parent[i] gives each node's parent). Directly linked houses cannot both be robbed.
Problem: Rob houses arranged as a tree (node 0 is the root; parent[i] gives each node's parent). Directly linked houses cannot both be robbed.
val = [2, 9, 3, 7, 1, 4, 5]
parent = [-1, 0, 0, 1, 1, 2, 2]
kids = [[] for _ in val]
for i, p in enumerate(parent):
if p >= 0: kids[p].append(i)
def go(u):
take, skip = val[u], 0
for c in kids[u]:
t, s = go(c)
take += s; skip += max(t, s)
return take, skip
print(max(go(0)))What is printed?- A. 18
- B. 19
- C. 21
- D. 12
Correct answer: B. 19
Each node returns (take, skip): taking the root 2 plus the four leaves 7, 1, 4, 5 gives 19, while the best without the root is max(9, 8) + max(3, 9) = 18. Greedily grabbing the largest value 9 gives 18; treating val as a linear street (house robber on the array) gives 21; taking the whole middle level 9 + 3 gives 12.
More Coding Interview Problems questions
- Problem: Keep the k-th largest score of a live leaderboard with a size-k min-heap and log the k-th largest once at least k scores have…
- Problem: From index 0, a[i] is the longest jump allowed from i. Find the minimum number of jumps to reach the last index (greedy BFS by…
- Problem: Split a string into as many parts as possible so that each letter appears in at most one part; return the part sizes. python def…
- How many structurally different binary search trees can be built on the keys 1..7 if the ROOT must be 3?
- Problem: Count the ways to tile a 2 × n board with 2 × 1 dominoes and L-shaped trominoes (both rotatable). python def tilings(n): dp = [1…
- What is the time complexity of this loop? python i = n while i > 0: for j in range(i): work() # O(1) i //= 2