Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Count the ways to make amount 5 from coins [1, 2, 5]. A developer wrote the loops in this order.

Problem: Count the ways to make amount 5 from coins [1, 2, 5]. A developer wrote the loops in this order.
def ways(coins, amt):
    dp = [1] + [0] * amt
    for a in range(1, amt + 1):
        for c in coins:
            if c <= a: dp[a] += dp[a - c]
    return dp[amt]
print(ways([1, 2, 5], 5))
What is printed?
  1. A. 4
  2. B. 8
  3. C. 5
  4. D. 9

Correct answer: D. 9

With the amount loop outside, every ORDER of coins is counted separately (1+2+2, 2+1+2, … are different), so it counts compositions: 1, 1, 2, 3, 5, 9. Putting the coin loop outside counts combinations and would give 4.

More Coding Interview Problems questions

Exams that ask this topic