forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoin-change.cpp
More file actions
21 lines (20 loc) · 765 Bytes
/
coin-change.cpp
File metadata and controls
21 lines (20 loc) · 765 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Time: O(n * k), n is the number of coins, k is the amount of money
// Space: O(k)
// DP solution. (164ms)
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> amounts(amount + 1, numeric_limits<int>::max());
amounts[0] = 0;
for (int i = 0; i <= amount; ++i) {
if (amounts[i] != numeric_limits<int>::max()) {
for (const auto& coin : coins) {
if (coin <= numeric_limits<int>::max() - i && i + coin <= amount) {
amounts[i + coin] = min(amounts[i + coin], amounts[i] + 1);
}
}
}
}
return amounts[amount] == numeric_limits<int>::max() ? -1 : amounts[amount];
}
};