Bird
Raised Fist0

Given the following space-optimized code for counting ways to make change, what is the output when coins = [1, 2, 5] and amount = 5?

easy🧾 Code Trace Q3 of Q15
Dynamic Programming: Knapsack - Number of Ways to Make Change
Given the following space-optimized code for counting ways to make change, what is the output when coins = [1, 2, 5] and amount = 5?
A4
B5
C6
D7
Step-by-Step Solution
Solution:
  1. Step 1: Trace dp array updates

    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,4].
  2. Step 2: Return dp[5]

    dp[5] = 4, representing 4 ways to make 5 with coins [1,2,5].
  3. Step 3: Re-examine counting

    Actually, the number of combinations is 4, but 7 says 7, which is incorrect. The correct answer is 4.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Counted combinations: 5,1; 2,2,1; 1x5; 2,1,1,1 -> 4 ways [OK]
Quick Trick: Trace dp array updates carefully [OK]
Common Mistakes:
MISTAKES
  • Off-by-one in dp indexing
  • Counting permutations instead of combinations
  • Mis-updating dp array
Trap Explanation:
PITFALL
  • Candidates often confuse permutations with combinations, leading to overcounting.
Interviewer Note:
CONTEXT
  • Tests ability to mentally execute DP code and understand state updates.
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