Challenge - 5 Problems
Coin Change Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of minimum coins for amount 11
What is the output of the following C++ code that calculates the minimum number of coins needed to make amount 11 using coins {1, 2, 5}?
DSA C++
int coins[] = {1, 2, 5}; int amount = 11; int n = sizeof(coins)/sizeof(coins[0]); int dp[12]; dp[0] = 0; for (int i = 1; i <= amount; i++) { dp[i] = amount + 1; for (int j = 0; j < n; j++) { if (coins[j] <= i) { dp[i] = std::min(dp[i], dp[i - coins[j]] + 1); } } } std::cout << dp[amount] << std::endl;
Attempts:
2 left
💡 Hint
Think about the fewest coins that add up to 11 using 1, 2, and 5.
✗ Incorrect
The minimum coins to make 11 are 5 + 5 + 1, which is 3 coins.
🧠 Conceptual
intermediateUnderstanding the base case in Coin Change DP
In the coin change minimum coins dynamic programming solution, what is the purpose of setting dp[0] = 0?
Attempts:
2 left
💡 Hint
Think about how many coins you need to make zero amount.
✗ Incorrect
dp[0] = 0 means no coins are needed to make amount zero, which is the base case for building solutions.
🔧 Debug
advancedIdentify the error in this Coin Change code snippet
What error will this C++ code produce when trying to find minimum coins for amount 7 with coins {2, 4}?
int coins[] = {2, 4};
int amount = 7;
int n = sizeof(coins)/sizeof(coins[0]);
int dp[8];
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
dp[i] = amount + 1;
for (int j = 0; j < n; j++) {
if (coins[j] <= i) {
dp[i] = std::min(dp[i], dp[i - coins[j]] + 1);
}
}
}
std::cout << dp[amount] << std::endl;
Attempts:
2 left
💡 Hint
Check if amount 7 can be formed by coins 2 and 4.
✗ Incorrect
Amount 7 cannot be formed by coins 2 and 4, so dp[7] remains amount+1 (8), indicating no solution.
🚀 Application
advancedMinimum coins for amount 0 with any coin set
What is the minimum number of coins needed to make amount 0 using any set of coins?
Attempts:
2 left
💡 Hint
Think about how many coins you need to make zero amount.
✗ Incorrect
No coins are needed to make amount zero, so the answer is 0.
❓ Predict Output
expertOutput of minimum coins for amount 10 with coins {3, 7}
What is the output of the following C++ code that calculates the minimum number of coins needed to make amount 10 using coins {3, 7}?
int coins[] = {3, 7};
int amount = 10;
int n = sizeof(coins)/sizeof(coins[0]);
int dp[11];
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
dp[i] = amount + 1;
for (int j = 0; j < n; j++) {
if (coins[j] <= i) {
dp[i] = std::min(dp[i], dp[i - coins[j]] + 1);
}
}
}
if (dp[amount] > amount) std::cout << -1 << std::endl;
else std::cout << dp[amount] << std::endl;
Attempts:
2 left
💡 Hint
Check if amount 10 can be formed by coins 3 and 7.
✗ Incorrect
Amount 10 can be formed by 7 + 3, which is 2 coins, so output is 2.
