ProgrammingHardInfosys · Cognizant

Children have ratings r = [1, 0, 2, 2, 1]. Each child gets at least one candy, and a child with a higher rating than a neighbour gets more candies than that neighbour. The two-pass greedy below assigns candies. What is the total printed?

Children have ratings r = [1, 0, 2, 2, 1]. Each child gets at least one candy, and a child with a higher rating than a neighbour gets more candies than that neighbour. The two-pass greedy below assigns candies. What is the total printed?
c = [1,1,1,1,1]
left to right: if r[i] > r[i-1] then c[i] = c[i-1] + 1
right to left: if r[i] > r[i+1] then c[i] = max(c[i], c[i+1] + 1)
Print sum of c
  1. A. 6
  2. B. 8
  3. C. 7
  4. D. 5

Correct answer: B. 8

The left pass gives 1, 1, 2, 1, 1. The right pass then raises index 3 to 2 (its rating beats the last child) and index 0 to 2 (its rating beats index 1), so the total is 8. Using only the left pass gives 6, the right pass alone gives a different sum, and giving each child one candy gives 5.

More Pseudocode and Code Tracing questions

Exams that ask this topic