Advertisement
pkbagchi

Coin Change DP

Apr 4th, 2019
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.08 KB | None | 0 0
  1. // A Dynamic Programming based C++ program to find minimum of coins
  2. // to make a given change V
  3. #include<bits/stdc++.h>
  4. using namespace std;
  5.  
  6. // m is size of coins array (number of different coins)
  7. int minCoins(int coins[], int m, int V)
  8. {
  9.     // table[i] will be storing the minimum number of coins
  10.     // required for i value. So table[V] will have result
  11.     int table[V+1];
  12.  
  13.     // Base case (If given value V is 0)
  14.     table[0] = 0;
  15.  
  16.     // Initialize all table values as Infinite
  17.     for (int i=1; i<=V; i++)
  18.         table[i] = INT_MAX;
  19.  
  20.     // Compute minimum coins required for all
  21.     // values from 1 to V
  22.     for (int i=1; i<=V; i++)
  23.     {
  24.         // Go through all coins smaller than i
  25.         for (int j=0; j<m; j++)
  26.         if (coins[j] <= i)
  27.         {
  28.             int sub_res = table[i-coins[j]];
  29.             if (sub_res != INT_MAX && sub_res + 1 < table[i])
  30.                 table[i] = sub_res + 1;
  31.         }
  32.     }
  33.    
  34.     return table[V];
  35. }
  36.  
  37. // Driver program to test above function
  38. int main()
  39. {
  40.     int coins[] = {1,5,6,8};
  41.     int m = sizeof(coins)/sizeof(coins[0]);
  42.     int V = 11;
  43.     cout << "Minimum coins required is "
  44.         << minCoins(coins, m, V);
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement