-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoinChange.cpp
More file actions
49 lines (39 loc) · 1.35 KB
/
coinChange.cpp
File metadata and controls
49 lines (39 loc) · 1.35 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
/*You are given coins of different denominations and a total amount of money amount. Write a function to compute 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.
Example 1:
Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins = [2], amount = 3
Output: -1
Note:
You may assume that you have an infinite number of each kind of coin.*/
int coinChange(vector<int>& denom, int change)
{
int size = denom.size();
if(change ==0)
return 0;
vector<int> coinArray(change+1,INT_MAX);
coinArray[0] = 0;
//For every number
for(int i=1;i<= change;i++)
{
int min = INT_MAX;
//Checking every coin
for(int j=0;j<size;j++)
{
if(i - denom[j] >=0)
{
int coinsReq = coinArray[(i-denom[j])];
if(coinsReq != INT_MAX)
coinsReq++;
if(min > coinsReq)
{min = coinsReq;}
}
}
coinArray[i] = min;
}
if(coinArray[change] == INT_MAX)
return -1;
return coinArray[change];
}