Data Structures & AlgorithmsEasyProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the fewest coins that make an amount (−1 if impossible).

Problem: Find the fewest coins that make an amount (−1 if impossible).
def coins(cs, amt):
    INF = float('inf'); dp = [0] + [INF] * amt
    for a in range(1, amt + 1):
        for c in cs:
            if c <= a and dp[a - c] + 1 < dp[a]:
                dp[a] = dp[a - c] + 1
    return dp[amt] if dp[amt] != INF else -1
print(coins([1, 5, 6, 9], 11), coins([2], 3), coins([3, 7], 0))
What is printed?
  1. A. 3 -1 0
  2. B. 2 -1 1
  3. C. 2 -1 0
  4. D. 2 0 0

Correct answer: C. 2 -1 0

dp[a] = 1 + min dp[a − c]. 11 = 5 + 6 (2 coins), while greedy 9 + 1 + 1 uses 3. Odd 3 with coin 2 is impossible → −1. Amount 0 needs 0 coins. O(amount × coins).

More Coding Interview Problems questions

Exams that ask this topic