Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Children stand in a line with ratings; each gets ≥ 1 candy and a child with a higher rating than a NEIGHBOUR must get more than that neighbour. Find the minimum total.

Problem: Children stand in a line with ratings; each gets ≥ 1 candy and a child with a higher rating than a NEIGHBOUR must get more than that neighbour. Find the minimum total.
def candy(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(candy([4, 6, 4, 5, 6, 2]))
What is printed?
  1. A. 9
  2. B. 10
  3. C. 8
  4. D. 16

Correct answer: B. 10

Left pass gives [1, 2, 1, 2, 3, 1]; the right pass changes nothing because each peak already exceeds its right neighbour, so the total is 10. Running only the right-to-left pass gives 8, overwriting with c[i+1] + 1 instead of taking the max gives 9, and handing out candies by global rating rank gives 16.

More Coding Interview Problems questions

Exams that ask this topic