Bird
Raised Fist0

Given the following code, what is the output when coins = [1, 2, 5] and amount = 5?

easy🧾 Code Trace Q12 of Q15
Dynamic Programming: Knapsack - Number of Ways to Make Change
Given the following code, what is the output when coins = [1, 2, 5] and amount = 5?
def count_ways_space_opt(coins, amount):
    dp = [0] * (amount + 1)
    dp[0] = 1
    for coin in coins:
        for w in range(coin, amount + 1):
            dp[w] += dp[w - coin]
    return dp[amount]

coins = [1, 2, 5]
amount = 5
print(count_ways_space_opt(coins, amount))
A4
B7
C5
D6
Step-by-Step Solution
Solution:
  1. Step 1: Trace dp array updates for each coin

    Start dp = [1,0,0,0,0,0]. After coin=1, dp = [1,1,1,1,1,1]. After coin=2, dp = [1,1,2,2,3,3]. After coin=5, dp = [1,1,2,2,3,6].
  2. Step 2: Confirm dp[5] value

    dp[5] = 6, representing 6 ways to make amount 5 with coins [1,2,5].
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Manual dp tracing matches output 6 [OK]
Quick Trick: DP accumulates counts incrementally per coin [OK]
Common Mistakes:
MISTAKES
  • Off-by-one in dp indexing
  • Miscounting after last coin iteration
  • Confusing permutations with combinations
Trap Explanation:
PITFALL
  • Counting permutations or misindexing dp leads to wrong totals; careful incremental updates are key.
Interviewer Note:
CONTEXT
  • Tests ability to mentally execute DP code and track array state.
Master "Number of Ways to Make Change" in Dynamic Programming: Knapsack

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Dynamic Programming: Knapsack Quizzes