Challenge: Fewest Coins (DP)
Completed
Print the fewest coins that make the amount exactly (coins reusable), or -1.
Input
Line 1: n amount (amount ≤ 10000). Line 2: n coin values.
Output
One number.
Example
Input
3 6 1 3 4
Output
2
Editor
C++
Hints
best[0] = 0; everything else starts at 'impossible'.
best[a] = 1 + min over coins c ≤ a of best[a - c].
Solution explanation
O(amount × coins), always the true minimum.
Show solution
#include <algorithm>
#include <climits>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, amount;
cin >> n >> amount;
vector<int> coins(n);
for (int& c : coins) cin >> c;
vector<int> best(amount + 1, INT_MAX);
best[0] = 0;
for (int a = 1; a <= amount; a++)
for (int c : coins)
if (c <= a && best[a - c] != INT_MAX) best[a] = min(best[a], best[a - c] + 1);
cout << (best[amount] == INT_MAX ? -1 : best[amount]) << endl;
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module