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
- A. 6
- B. 8
- C. 7
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Let x = 0. For i from 1 to 10: if i mod 3 == 0 then x = x + i, otherwise x = x - 1. What is printed? x = 0 for i = 1 to 10 if i mod 3 == 0…
- A rope of length L is cut into two parts of lengths floor(L/2) and L - floor(L/2) whenever its length is 2 or more; the cost of a cut is…
- Jobs each take one unit of time and carry a deadline: 1, 1, 2, 3, 4, 4 (the last slot the job may use; slots are 1, 2, 3, ...). The…
- Events (start, end) are attended one per day, and an event may be attended on any day from start to end inclusive. Events: (1,2), (1,2)…
- Seven tasks with durations 7, 5, 4, 3, 2, 2, 1 are assigned to two identical machines. Tasks are taken in decreasing duration order, and…
- Array a = [2, 5, 3, 5]. For every pair of positions i < j, count the pairs where a[i] is at most a[j] (a[i] <= a[j]). What is the printed…