Problem: find the number of distinct quantities of money that a pile of coins can make.
The vector coins
contains the values of the coins, and the corresponding vector quantity
contains the number of coin there are (let's say coins = {1}
and quantity = {5}
, this means I have 5 pennies).
Although I have solved this problem, I would like to make it more time efficient. Could someone give me some pointers?
Miscellaneous info: the variable ctq
stands for "coins to quantity". I solved this by systematically iterating through all possible combinations of coins and putting their sum into a set. There has to be a better way to solve this problem, because this problem is supposed to be a dynamic programming question and I solved this problem without any knowledge of what that's supposed to be.
#include<iostream>
#include<vector>
#include<map>
#include<set>
int money(std::map<int, int> x)
{
int sum=0;
for(auto it=x.begin(); it!=x.end(); ++it)
{
sum+=it->first*it->second;
}
return sum;
}
int rec
(
std::set<int> &sums,
std::map<int, int> ctq,
std::vector<int> coins,
std::vector<int> quantity,
int m
)
{
for(int k=quantity[m]; k>=0; k--)
{
ctq[coins[m]] = k;
sums.insert(money(ctq));
if(m != 0)
{
rec(sums, ctq, coins, quantity, m-1);
}
}
return sums.size()-1;
}
int possibleSums(std::vector<int> coins, std::vector<int> quantity)
{
std::map<int, int> ctq;
for(std::size_t i=0; i<coins.size(); i++)
{
if(ctq.find(coins[i]) == ctq.end())
{
ctq.insert(std::make_pair(coins[i], quantity[i]));
}
else
{
ctq[coins[i]] += quantity[i];
}
}
std::vector<int> n_coins, n_quantity;
for(auto it = ctq.begin(); it != ctq.end(); ++it)
{
n_coins.push_back(it->first);
n_quantity.push_back(it->second);
}
std::set<int> sums;
return rec(sums, ctq, n_coins, n_quantity, n_coins.size()-1);
}
int main()
{
std::vector<int> coins = {10, 50, 100, 200};
std::vector<int> quantity = {511, 22, 30, 50};
std::cout << possibleSums(coins, quantity) << "\n";
return 0;
}