ProgrammingModerateInfosys · Cognizant
Coin denominations are 1, 4 and 5. The greedy method for amount 8 considers denominations from largest to smallest and takes each coin while it still fits. What is printed?
Coin denominations are 1, 4 and 5. The greedy method for amount 8 considers denominations from largest to smallest and takes each coin while it still fits. What is printed?
amount = 8; count = 0
for each coin in (largest to smallest)
while amount >= coin
amount = amount - coin
count = count + 1
end while
end for
Print count- A. 8
- B. 1
- C. 2
- D. 4
Correct answer: D. 4
Largest first takes 5 once and then three 1s, for four coins. Ascending order needs eight coins, and the optimum 4+4 (two coins) shows the greedy is not optimal for this coin set; stopping after the first denomination prints 1.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Fractional knapsack with capacity 50. Items as (value, weight): (60,10), (100,20), (120,30). Items are sorted by value per unit weight…
- Gas stations on a circle: gas = [1,2,3,4,5], cost = [3,4,5,1,2]. Station i gives gas[i] and then costs cost[i] to leave for station i+1…
- Ropes are to be merged into one. Merging two ropes of lengths a and b costs a + b and yields one rope of length a + b. Ropes have lengths…
- Stock prices by day: 3, 8, 2, 9, 1, 6. One share may be bought once and sold once later (later day only). The procedure below runs. What…
- Currency notes are paid out greedily from the largest denomination down, using as many notes of each denomination as possible. For amount…
- A number is given as the digit string 1432219. Exactly 3 digits must be deleted (the digits keep their order) so that the remaining number…