Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Each child must get at least one sweet, and a child with a higher rating than a neighbour must get more than that neighbour. Find the minimum sweets.
Problem: Each child must get at least one sweet, and a child with a higher rating than a neighbour must get more than that neighbour. Find the minimum sweets.
def sweets(r):
n = len(r); c = [1] * n
for i in range(1, n):
if r[i] > r[i - 1]: c[i] = c[i - 1] + 1
for i in range(n - 2, -1, -1):
if r[i] > r[i + 1]: c[i] = max(c[i], c[i + 1] + 1)
return sum(c)
print(sweets([1, 0, 2]), sweets([1, 2, 2]), sweets([1, 3, 4, 5, 2]))What is printed?- A. 5 5 11
- B. 5 4 10
- C. 5 4 11
- D. 4 4 11
Correct answer: C. 5 4 11
Left pass enforces the rule against the left neighbour, right pass against the right one; max keeps both. [1,0,2] → 2,1,2 = 5. [1,2,2] → 1,2,1 = 4 (equal ratings need not be equal). [1,3,4,5,2] → 1,2,3,4,1 = 11. O(n).
More Coding Interview Problems questions
- Problem: Each position holds the maximum jump length from it. Return the minimum jumps to reach the last index. python def jumps(a): j =…
- Problem: Can you reach the last index if a[i] is the maximum jump from i? java static boolean canReach(int[] a) { int far = 0; for (int i…
- Problem: Coins of denominations {1, 7, 10} are available in unlimited supply. Pay 14 with the fewest coins. What does the greedy 'largest…
- Problem: Split a string into as many parts as possible so each letter appears in at most one part; return the part sizes. python def…
- Problem: Jobs have deadlines and profits; each takes one unit of time. Schedule to maximise profit (greedy by profit, latest free slot)…
- Problem: Given n ≤ 10⁵ intervals, find the minimum number of points such that every interval contains at least one point. Which greedy…