ProgrammingVery hardCAT · MBA placement

What is printed?

What is printed?
def greedy(coins, amt):
    cnt = 0
    for c in sorted(coins, reverse=True):
        cnt += amt // c
        amt %= c
    return cnt if amt == 0 else -1
print(greedy([1, 3, 4], 6))
  1. A. 3
  2. B. 2
  3. C. 4
  4. D. -1

Correct answer: A. 3

Largest-first greedy takes 4, then 1 and 1, which is 3 coins. The optimal answer is 3 + 3, which uses only 2 coins, so greedy is not safe for arbitrary coin sets.

More Python Programming questions

Exams that ask this topic