Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Houses stand in a CIRCLE (the first and last are neighbours); adjacent houses cannot both be robbed.
Problem: Houses stand in a CIRCLE (the first and last are neighbours); adjacent houses cannot both be robbed.
def rob_line(a):
take = skip = 0
for x in a: take, skip = skip + x, max(take, skip)
return max(take, skip)
def rob_circle(a):
if len(a) == 1: return a[0]
return max(rob_line(a[:-1]), rob_line(a[1:]))
print(rob_circle([6, 2, 9, 4, 7]), rob_line([6, 2, 9, 4, 7]))What is printed?- A. 22 22
- B. 15 22
- C. 16 22
- D. 16 16
Correct answer: C. 16 22
In a line, 6 + 9 + 7 = 22 is best, but in a circle 6 and 7 are neighbours. Excluding the last house gives 6 + 9 = 15; excluding the first gives 9 + 7 = 16, so the circle answer is 16.
More Coding Interview Problems questions
- Problem: Each person is [h, k]: height h, and exactly k people in front are at least as tall. Rebuild the queue (sort tallest first…
- Problem: 2n people must be split so n fly to city A and n to city B; costs[i] = [costA, costB]. Minimise total cost (sort by costA −…
- Problem: Can the cards be split into groups of W consecutive values? python from collections import Counter def straights(hand, W): if…
- Problem: Report the median of every window of size k (sorted-list version with bisect). python from bisect import insort, bisectleft def…
- Problem: A single-threaded CPU receives tasks [enqueueTime, processingTime]. When idle it runs the available task with the shortest…
- Problem: A min-stack supports push, pop, top and getMin in O(1) by storing (value, current minimum) pairs. python st, out = [], [] def…