Data Structures & AlgorithmsHardProduct Company SDE · greedy round

Problem: Children stand in a line with ratings [1, 0, 2]. Each child gets at least one candy, and a child with a higher rating than a neighbour gets more candies. What is the minimum total number of candies? Run the two-pass code.

Problem: Children stand in a line with ratings [1, 0, 2]. Each child gets at least one candy, and a child with a higher rating than a neighbour gets more candies. What is the minimum total number of candies? Run the two-pass code.
r = [1, 0, 2]
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)
print(sum(c))
What is printed?
  1. A. 5
  2. B. 4
  3. C. 6
  4. D. 3

Correct answer: A. 5

The left-to-right pass gives [1, 1, 2] and the right-to-left pass fixes the first child to 2, giving [2, 1, 2] with total 5. Using only one pass gives 4 and violates the rule for the first child.

More Coding Interview Problems questions

Exams that ask this topic