Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Taking a value v earns v points for EVERY copy of v, but then all copies of v − 1 and v + 1 are deleted. Maximise the points (house robber over values).
Problem: Taking a value v earns v points for EVERY copy of v, but then all copies of v − 1 and v + 1 are deleted. Maximise the points (house robber over values).
from collections import Counter
def earn(a):
c = Counter(a); take = skip = 0; prev = None
for v in sorted(c):
gain = v * c[v]
if prev is not None and v == prev + 1:
take, skip = skip + gain, max(take, skip)
else:
take, skip = max(take, skip) + gain, max(take, skip)
prev = v
return max(take, skip)
print(earn([2, 2, 3, 3, 3, 4, 6, 6]))What is printed?- A. 21
- B. 17
- C. 14
- D. 25
Correct answer: A. 21
Points per value: 2 → 4, 3 → 9, 4 → 4, 6 → 12. 2, 3, 4 are consecutive, so choose 3 (9) or 2 + 4 (8); 6 is independent (12). Best: 9 + 12 = 21, confirmed by brute force over value subsets.
More Coding Interview Problems questions
- Problem: Travel on given days; passes cost costs[0] (1 day), costs[1] (7 days) and costs[2] (30 days). Minimise the total cost. python def…
- Problem: Houses stand in a CIRCLE (the first and last are neighbours); adjacent houses cannot both be robbed. python def robline(a): take…
- 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…