-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoin_change_dp.cpp
More file actions
63 lines (53 loc) · 1.1 KB
/
coin_change_dp.cpp
File metadata and controls
63 lines (53 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <bits/stdc++.h>
using namespace std;
//bottom up approach
int coinChangeMin(vector<int> &coins, int amount) {
const int INF = 1e9;
vector<int> dp(amount + 1, INF);
dp[0] = 0;
for (int coin : coins) {
for (int i = coin; i <= amount; ++i) {
dp[i] = min(dp[i], dp[i - coin] + 1);
}
}
return dp[amount] == INF ? -1 : dp[amount];
}
int main() {
vector<int> coins = {1, 2, 5};
int amount = 11;
cout << coinChangeMin(coins, amount) << "\n"; // Output: 3 (5+5+1)
}
//top-down approach
unordered_map<int,int> mp;
int min_coins(int tot)
{
if(tot==0)
return 0;
if(mp.find(tot)!=mp.end())
return mp[tot];
int mncoin = INT_MAX;
for(auto i:coins)
{
if(i<=tot)
{
int sub = min_coins(tot-i);
mncoin = min(mncoin,sub+1);
}
}
mp[tot] = mncoin;
return mncoin;
}
// Driver Code
int main()
{
Faster;
ll tc = 1, test = 1;
cin >> tc;
while(tc--)
{
int n;
cin >> n;
int ans = min_coins(n);
cout << ans << nl;
}
}