Skip to main content

Coin Change

Problem

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

Solution Approach

Expected Time complexity: O(n2)O(n^2)

Click - to see solution code
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<long long> changes(amount + 1, INT_MAX);
changes[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int j = 0; j < coins.size(); j++) {
if (coins[j] <= i) {
changes[i] = min(changes[i], changes[i - coins[j]] + 1);
}
}
}
if (changes[amount] == INT_MAX) return -1;
return changes[amount];
}
};