Number of Coins
Problem
Section titled “Problem”Given a value V and array coins[] of size M, the task is to make the change for V cents, given that you have an infinite supply of each of coins - coins1, coins2, ..., coinsm valued coins. Find the minimum number of coins to make the change. If not possible to make change then return -1.
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”This is an unbounded knapsack: every coin can be used any number of times, and we want the fewest coins whose values add up to V. Let dp[i][j] be the minimum number of coins, using only the first i coin types, that sum to exactly j. Trying every combination of coins directly is exponential, but each state depends only on two smaller states.
For the i-th coin there are two choices:
- Take it (it stays available, since coins are unlimited):
- Skip it:
Algorithm
Section titled “Algorithm”- Sort
coins(not needed for correctness) and create a(M + 1) x (V + 1)tabledpfilled withINT_MAX, meaning “not reachable”. It useslong longso thatINT_MAX + 1does not overflow. - For each coin index
ifrom1toM, setdp[i][0] = 0, since zero coins make sum0. - For each sum
jfrom1toV, apply the “take” transition whencoins[i - 1] <= j, then the “skip” transition. - If
dp[M][V]is still at leastINT_MAX, the sum cannot be formed, so return-1; otherwise returndp[M][V].
Complexity
Section titled “Complexity”- Time: — every cell of the
dptable is filled once in ; sorting adds only . - Space: — the full 2D
dptable.
Edge cases
Section titled “Edge cases”- Unreachable value, e.g.
coins = [2],V = 3: the cell stays atINT_MAXand the function returns-1.
class Solution { public: int minCoins(int coins[], int M, int V) { sort(coins, coins + M); vector<vector<long long>> dp(M + 1, vector<long long>(V + 1, INT_MAX)); for (int i = 1; i <= M; i++) { dp[i][0] = 0; for (int j = 1; j <= V; j++) { if (coins[i - 1] <= j) { dp[i][j] = min(dp[i][j], dp[i][j - coins[i - 1]] + 1); } dp[i][j] = min(dp[i][j], dp[i - 1][j]); } } if (dp[M][V] >= INT_MAX) return -1; return (int)dp[M][V]; }};Give it a try first
Attempt the problem on GeeksforGeeks — the code will still be here.