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?
  1. A. 21
  2. B. 17
  3. C. 14
  4. 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

Exams that ask this topic