-
Notifications
You must be signed in to change notification settings - Fork 1
/
Minimum Coins DP
43 lines (38 loc) · 1.18 KB
/
Minimum Coins DP
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
#include <bits/stdc++.h>
// int f(int i, int T, vector<int> &num, vector<vector<int>> &dp){
// if(i == 0){
// if(T % num[0] == 0) return T/num[0];
// else return 1e9;
// }
// if(dp[i][T] != -1) return dp[i][T];
// int notTake = 0 + f(i-1, T, num, dp);
// int take = INT_MAX;
// if(num[i]<=T) take = 1 + f(i, T - num[i], num, dp);
// return dp[i][T] = min(take, notTake);
// }
int minimumElements(vector<int> &num, int x)
{
int n = num.size();
// vector<vector<int>> dp(n, vector<int> (x+1, -1));
// int ans = f(n-1, x, num, dp);
// if(ans >= 1e9) return -1;
// else return ans;
// Write your code here.
//tabulation Method
vector<vector<int>> dp(n, vector<int> (x+1, 0));
for(int T = 0; T<=x; T++){
if(T%num[0] == 0) dp[0][T] = T/num[0];
else dp[0][T] = 1e9;
}
for(int i=1;i<n;i++){
for(int T=0;T<=x;T++){
int notTake = 0 + dp[i-1][T];
int take = INT_MAX;
if(num[i]<=T) take = 1 + dp[i][T - num[i]];
dp[i][T] = min(take, notTake);
}
}
int ans = dp[n-1][x];
if(ans>=1e9) return -1;
else return ans;
}