ProgrammingHardInfosys · Cognizant
Coin denominations are 1, 4 and 6. The greedy method below pays amount 8 by always taking the largest coin that still fits (coins are reused). What is the number of coins printed?
Coin denominations are 1, 4 and 6. The greedy method below pays amount 8 by always taking the largest coin that still fits (coins are reused). What is the number of coins printed?
amount = 8; count = 0
for each coin in (6, 4, 1) from largest to smallest
while amount >= coin: amount = amount - coin; count = count + 1
end for
Print count- A. 3
- B. 8
- C. 2
- D. 1
Correct answer: A. 3
Largest first takes 6, then 1 and 1, for three coins. The optimum 4+4 uses two coins, ascending order takes eight 1s, and stopping after the first denomination pays only one coin.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Ropes of lengths 1, 2, 3, 4 and 5 are merged two at a time with cost equal to the sum of the two lengths. The greedy merges the two…
- A truck carries at most 10 boxes. The box types are given as (units per box, number of boxes): (5, 3), (4, 2), (3, 4), (2, 5). The greedy…
- The greedy below repeatedly increases the smallest element of the array [3, 1, 2] by 1, three times in total. What is the minimum value of…
- For the function gcd(a, b) written by the procedure below, what is printed for gcd(252, 105)? (The procedure uses repeated remainder…
- The Fibonacci numbers F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2) satisfy gcd(F(m), F(n)) = F(gcd(m, n)). The procedure below uses this…
- The procedure below computes the last digit of 7^100 by starting from d = 1 and multiplying by 7, keeping only the last digit, once for…