[Geeks for Geeks] Number of Coins

Number of Coins

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.

  • Time : O(nv)
  • Space : O(v)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int minCoins(int coins[], int n, int V) {
vector<int> dp(V + 1, INT_MAX);
dp[0] = 0;
for(int i = 0; i < n; i++) {
for(int j = coins[i]; j <= V; j++) {
if(dp[j-coins[i]] == INT_MAX) continue;
dp[j] = min(dp[j], dp[j-coins[i]] + 1);
}
}

return dp[V] == INT_MAX ? -1 : dp[V];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/22/PS/GeeksforGeeks/number-of-coins/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.