Sunday 17 July 2016

Coin Change

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.
Examples:
Input: coins[] = {25, 10, 5}, V = 30
Output: Minimum 2 coins required
We can use one coin of 25 cents and one of 5 cents 

Input: coins[] = {9, 6, 5, 1}, V = 11
Output: Minimum 2 coins required
We can use one coin of 6 cents and 1 coin of 5 cents


 int coinChange(int* coins, int m, int V) {  
   int table[V+1];  
   table[0] = 0;  
   for (int i = 1; i <= V; i++){  
     table[i] = INT_MAX;  
   }  
   for (int i = 1; i <= V; i++){  
     for (int j = 0; j < m; j++){  
      if (coins[j] <= i) {  
        int sub_res = table[i - coins[j]];  
        if (sub_res != INT_MAX && sub_res + 1 < table[i]){  
          table[i] = sub_res + 1;  
        }  
      }  
     }  
   }  
   return table[V] == INT_MAX ? -1 : table[V];  
 }  
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive