ProgrammingHardInfosys · Cognizant
Coins are 1, 5, 10, 21 and 25. To pay 63, the greedy method below always takes the largest coin that fits, using the list in descending order. What is the number of coins printed?
Coins are 1, 5, 10, 21 and 25. To pay 63, the greedy method below always takes the largest coin that fits, using the list in descending order. What is the number of coins printed?
amount = 63; coins = 0
for d in (25, 21, 10, 5, 1), largest first
k = amount div d; coins = coins + k; amount = amount - k * d
end for
Print coins- A. 63
- B. 7
- C. 3
- D. 6
Correct answer: D. 6
Greedy takes 25, 25, then 10, then 1, 1, 1 for six coins, while 21+21+21 uses only three. Ascending order takes sixty-three 1s, dropping the 10 coin gives 7 coins, and the true optimum 21+21+21 (three coins) is what the greedy misses.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Intervals (start, end): (1,10), (2,3), (4,5), (6,7), (8,9). The greedy below selects the largest set of pairwise disjoint intervals…
- Each event is (time, +1) for a train arriving or (time, -1) for a train departing. Arrivals are at 1, 3, 3, 5, 6, 8 and departures are at…
- Five numbers 3, 30, 34, 5, 9 are to be arranged to form the largest possible number. Two numbers x, y are put in the order that gives the…
- Prices by day: 1, 5, 3, 8, 6, 10. Profit is earned in every rise: whenever tomorrow's price is higher than today's, buy today and sell…
- Array a = [3, 1, 2, 5, 4] is sorted by bubble sort: in each pass adjacent pairs out of order are swapped (a[j] > a[j+1]). What is the…
- Items of weights 7, 3, 5, 2, 6 are considered in increasing weight order. Each item is taken if it still fits in the capacity 13. What is…