Minimum Number of Coins
Problem Statement:β
Given an infinite supply of each denomination of Indian currencyΒ 1, 2, 5, 10, 20, 50, 100, 200, 500, 2000 and a target value N.
Find the minimum number of coins and/or notes needed to make the change for Rs N. You must return the list containing the valueΒ of coins required.
-
Example:
β Solution 1: Greedy (Repeated Subtraction)β
vector<int> minPartition(int N) {
vector<int> coins = {1, 2, 5, 10, 20, 50, 100, 200, 500, 2000};
vector<int> res;
int n = coins.size();
for(int i = n - 1; i >= 0; i--){
while(N >= coins[i]){
N -= coins[i];
res.push_back(coins[i]);
}
}
return res;
}
β Solution 2: Greedy (Integer Division Optimized)β
vector<int> minPartition(int N) {
vector<int> coins = {1, 2, 5, 10, 20, 50, 100, 200, 500, 2000};
vector<int> res;
int n = coins.size();
for(int i = n - 1; i >= 0; i--){
if(N >= coins[i]){
int count = N / coins[i];
res.insert(res.end(), count, coins[i]); // Insert 'count' copies
N %= coins[i];
}
}
return res;
}
π Revision Notesβ
π How It Worksβ
- Youβre given an amount
Nand must return a list of coins that sum toNusing minimum number of coins. - The logic uses greedy selection of the largest coin possible at every step.
- Solution 1 subtracts repeatedly and pushes the coin each time.
- Solution 2 optimizes by computing how many times the coin fits and adds them all at once.
π§© Key Formula / Transitionβ
- For each coin:
- Use it while
coin <= N - In optimized:
count = N / coin, reduceN %= coin
- Use it while
β±οΈ Time & Space Complexityβ
| Solution | Time Complexity | Space Complexity |
|---|---|---|
| Repeated Subtraction | O(N) in worst-case (if only 1s) | O(N) |
| Integer Division | O(denominations) = O(10) | O(N) |
In practice, both are efficient due to large coins (like 2000, 500, etc.).
β οΈ Edge Casesβ
N = 0β should return empty vector.Nis already a coin β result will just be that coin.- Input beyond max denomination β handled by loop automatically.
π‘ Other Approachesβ
- Dynamic Programming (for variable coin values, not needed here).
- BFS (if coin set wasnβt sorted/greedy-safe β again not needed here).
π Related Problemsβ
- Coin Change (Leetcode 322) β DP variant.
- Minimum Coins (GFG)
- Fractional Knapsack (greedy logic)
- Coin Change II (ways to make sum)
π¬