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- A. 0
- B. 5
- C. 1
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Closed intervals (start, end): (1,4), (2,6), (8,10), (9,12), (11,13), (3,5). The greedy below places points so that every interval…
- Job durations (burst times) are 6, 8, 7, 3, 4 with all jobs arriving at time 0. Shortest-job-first runs them one after another in…
- A row of positions 1 to 20 is scanned in order. A position i is picked if no position has been picked yet, or if i minus the last picked…
- Array a = [2,3,1,1,4,2,1,3,1,1] (0-based). From index i you may jump forward at most a[i] positions. Starting at index 0, the greedy below…
- Tasks with the same letter must be separated by at least n = 2 idle or other slots. The task string is AAABBC. The greedy formula below…
- Items of sizes 5, 7, 5, 2, 4, 2, 5, 1, 6 are packed in this order into bins of capacity 10 using the first-fit rule: put each item into…