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?
  1. A. 5 5 11
  2. B. 5 4 10
  3. C. 5 4 11
  4. 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

Exams that ask this topic