ProgrammingHardTCS NQT · Accenture

Children have greed values 7, 8, 9, 10 and cookies have sizes 5, 6, 7, 8, 8. A child is content if the cookie given is at least his greed; each cookie goes to at most one child. Both lists are sorted and the greedy below runs. What is printed?

Children have greed values 7, 8, 9, 10 and cookies have sizes 5, 6, 7, 8, 8. A child is content if the cookie given is at least his greed; each cookie goes to at most one child. Both lists are sorted and the greedy below runs. What is printed?
sort greed ascending; sort cookies ascending
i = 0 (child), j = 0 (cookie)
while i < children and j < cookies
    if cookie[j] >= greed[i] then i = i + 1
    j = j + 1
end while
Print i
  1. A. 0
  2. B. 5
  3. C. 1
  4. D. 2

Correct answer: D. 2

Pairing the smallest cookie that satisfies the smallest remaining child keeps large cookies free, so two children are satisfied (by the 7 and 8 cookies). Leaving the greed list unsorted gives 0, counting cookies used gives 5, and demanding a strictly larger cookie gives 1.

More Pseudocode and Code Tracing questions

Exams that ask this topic