Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: Picking a value v earns v points but deletes every v − 1 and v + 1 from the array; repeat until empty. Maximise points (reduces to house robber over sorted distinct values).

Problem: Picking a value v earns v points but deletes every v − 1 and v + 1 from the array; repeat until empty. Maximise points (reduces to house robber over sorted distinct values).
from collections import Counter
def earn(nums):
    c = Counter(nums); take = skip = 0; prev = None
    for v in sorted(c):
        gain = v * c[v]
        if prev == v - 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([3, 4, 2, 4, 5, 3, 4]), earn([1, 1, 1, 2, 9]))
What is printed?
  1. A. 17 12
  2. B. 14 12
  3. C. 11 12
  4. D. 14 11

Correct answer: B. 14 12

Taking v once means taking all copies (gain v·count), and adjacent values conflict like adjacent houses. First: gains 2 → 2, 3 → 6, 4 → 12, 5 → 5; best is 2 + 12 = 14 (3 + 5 gives 11). Second: 1s give 3 and 2 gives 2, so 3 + 9 = 12 beats 2 + 9. Non-adjacent values (here 9) can always be added. O(n log n).

More Coding Interview Problems questions

Exams that ask this topic