Bird
Raised Fist0

Consider the following Python code for counting the number of ways to make change. What is the output when calling change(5, [1, 2, 5])?

easy🧾 Code Trace Q12 of Q15
Dynamic Programming: Knapsack - Coin Change II (Count Ways)
Consider the following Python code for counting the number of ways to make change. What is the output when calling change(5, [1, 2, 5])?
A5
B3
C4
D6
Step-by-Step Solution
Solution:
  1. Step 1: Initialize dp array

    dp = [1,0,0,0,0,0] since dp[0]=1.
  2. Step 2: Update dp for each coin

    For coin=1: dp becomes [1,1,1,1,1,1]; for coin=2: dp updates to [1,1,2,2,3,3]; for coin=5: dp updates to [1,1,2,2,3,4].
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    dp[5] = 4 matches known output [OK]
Quick Trick: Trace dp updates coin by coin [OK]
Common Mistakes:
MISTAKES
  • Off-by-one in dp indexing
  • Confusing permutations with combinations
Trap Explanation:
PITFALL
  • Counting permutations would yield 6, but this code counts combinations correctly.
Interviewer Note:
CONTEXT
  • Tests ability to mentally execute DP code and track array updates.
Master "Coin Change II (Count Ways)" 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