I found a piece of code that I was writing for interview prep few months ago.
According to the comment I had, it was trying to solve this problem:
Given some dollar value in cents (e.g. 200 = 2 dollars, 1000 = 10 dollars), find all the combinations of coins that make up the dollar value. There are only pennies, nickels, dimes, and quarters allowed. (quarter = 25 cents, dime = 10 cents, nickel = 5 cents, penny = 1 cent)
For example, if 100 was given, the answer should be:
4 quarter(s) 0 dime(s) 0 nickel(s) 0 pennies
3 quarter(s) 1 dime(s) 0 nickel(s) 15 pennies
etc.
This can be solved in both iterative and recursive ways, I believe. My recursive solution is quite buggy, and I was wondering how other people would solve this problem. The difficult part of this problem was making it as efficient as possible.
Java solution
}
Let C(i,J) the set of combinations of making i cents using the values in the set J.
You can define C as that:
(first(J) takes in a deterministic way an element of a set)
It turns out a pretty recursive function... and reasonably efficient if you use memoization ;)
The below java solution which will print the different combinations as well. Easy to understand. Idea is
for sum 5
The solution is
If the remaining sum in each loop is lesser than the denomination ie if remaining sum 1 is lesser than 2, then just break the loop
The complete code below
Please correct me in case of any mistakes
}
This is a really old question, but I came up with a recursive solution in java that seemed smaller than all the others, so here goes -
Improvements:
If the currency system allows it, a simple greedy algorithm that takes as many of each coin as possible, starting with the highest value currency.
Otherwise, dynamic programming is required to find an optimal solution quickly since this problem is essentially the knapsack problem.
For example, if a currency system has the coins:
{13, 8, 1}
, the greedy solution would make change for 24 as{13, 8, 1, 1, 1}
, but the true optimal solution is{8, 8, 8}
Edit: I thought we were making change optimally, not listing all the ways to make change for a dollar. My recent interview asked how to make change so I jumped ahead before finishing to read the question.