Minimizing Coins

Consider a money system consisting of n coins. Each coin has a positive integer value. Your task is to produce a sum of money x using the available coins in such a way that the number of coins is minimal.

For example, if the coins are  and the desired sum is , an optimal solution is  which requires 3 coins.

Example:

Input:  n = 3, m = 11, a = {1, 5, 7}
Output: 3

Approach

C++

#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int INF = 1e9;

int minimizingCoins(int nint mvector<int&a)
{

    vector<intdp(m + 1INF);
    dp[0] = 0;
    for (int i = 1i <= mi++)
    {
        for (int j = 0j < nj++)
        {
            if (i - a[j] >= 0)
            {
                dp[i] = min(dp[i]dp[i - a[j]] + 1);
            }
        }
    }

    if (dp[m] < INF)
        return dp[m];
    return -1;
}

int main()
{

    int n = 3m = 11;

    vector<inta = {157};

    cout << minimizingCoins(nma<< "\n";

    return 0;
}


No comments:

Post a Comment