ProgrammingHardAmazon OA · Flipkart coding round

What is printed?

What is printed?
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([1, 0, 2]), candy([1, 2, 2]))
  1. A. 4 4
  2. B. 5 5
  3. C. 6 4
  4. D. 5 4

Correct answer: D. 5 4

Two passes give each child at least one more sweet than a lower-rated neighbour on each side. The first case needs 2, 1, 2 for a total of 5, and the second needs 1, 2, 1 for a total of 4.

More Python Programming questions

Exams that ask this topic