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?- A. 17 12
- B. 14 12
- C. 11 12
- 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
- Problem: Make two strings equal by deleting characters; the cost is the sum of ASCII codes of deleted characters. Minimise it (a weighted…
- Problem: Find the longest bitonic subsequence (strictly increasing then strictly decreasing; either part may be empty) using LIS from the…
- Problem: Numbers whose only prime factors are 2, 3 and 5 (1 included) are generated in order with three pointers. python def ugly(n): u =…
- Problem: A chess knight hops on a phone keypad (1-9 in a 3 × 3 grid, 0 below 8). Count the distinct numbers of length n it can dial (start…
- Problem: Trade a stock any number of times (hold at most one share); each completed sale pays a fixed fee. Maximise profit with two…
- Problem: Is c formed by interleaving a and b (keeping each string's internal order)? dp[i][j] = first i chars of a and j chars of b can…