Data Structures & AlgorithmsHardAmazon · Microsoft OA

Edge case: greedy coin change versus DP when the coin system is not canonical.

Edge case: greedy coin change versus DP when the coin system is not canonical.
def greedy(coins, x):
    cnt = 0
    for c in sorted(coins, reverse=True):
        cnt += x // c; x %= c
    return cnt
def dp(coins, x):
    best = [0] + [float('inf')] * x
    for a in range(1, x + 1):
        best[a] = min(best[a - c] + 1 for c in coins if c <= a)
    return best[x]
print(greedy([1, 3, 4], 6), dp([1, 3, 4], 6), greedy([1, 5, 10, 25], 30), dp([1, 5, 10, 25], 30))
What is printed?
  1. A. 2 2 2 2
  2. B. 3 2 2 2
  3. C. 3 2 5 2
  4. D. 2 3 2 2

Correct answer: B. 3 2 2 2

Greedy takes 4 + 1 + 1 = 3 coins for 6, but 3 + 3 uses 2. For the canonical US coins greedy is optimal: 30 = 25 + 5 (2 coins) both ways. Greedy is safe only for canonical coin systems.

More Coding Interview Problems questions

Exams that ask this topic