Data Structures & AlgorithmsModerateCognizant · Capgemini pattern

What is printed? (coin change: number of combinations)

What is printed? (coin change: number of combinations)
def ways(coins, amt):
    dp = [1] + [0] * amt
    for c in coins:
        for a in range(c, amt + 1): dp[a] += dp[a - c]
    return dp[amt]
print(ways([2, 5, 3, 6], 10), ways([1, 2, 3], 4))
  1. A. 6 4
  2. B. 5 4
  3. C. 5 7
  4. D. 4 4

Correct answer: B. 5 4

Coins in the outer loop count each multiset once. 10 from {2, 3, 5, 6}: 2+2+2+2+2, 2+2+3+3, 2+2+6, 2+3+5, 5+5 = 5. 4 from {1, 2, 3}: 1+1+1+1, 1+1+2, 2+2, 1+3 = 4. With the loops swapped you would count ordered sequences (7 for the second). O(amount × coins).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic