No one enjoys carrying around spare change. And to avoid all that jingling it's absolutely necessary to have an efficient algorithm to calculate the minimum number of coins needed to pay for something. So given a set of coin denominations determine the fewest number of coins required to add up to a given amount. Coin denominations WILL NOT be standard.
Example
US Currency includes the penny, nickel, dime and quarter or the coins with denominations: [1, 5, 10, 25] If I were to ask you to make 75 cents you would just return 3 since 75 cents can be made with 3 quarters.
Denominations:
coins1={1,5,10,25};
coins2={1,2,5,10,20,50};
Tests:
coins1(123)
coins2(123)
coins1(75)
coins2(75)
Good luck!
This challenge comes from RasPat1 on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (7)
That's not a good test suite. You want something that will break the naive implementation. Add
coins3={1,5,20,25}
coins3(40)
This was always my favorite part of Topcoder.
Not sure if this is an efficient solution but here is mine in JavaScript. I took the liberty to return an object instead of the number of coins and sorted the denominations instead of expecting it in order. I also added the test case suggested by davidmmooney.
the 'coins3,40' test returns the wrong answer it should be "20: 2"
Wow. I really liked this one. I ended up writing a lot of lines, but well documented. What I really wanted to showcase here is that sometimes, creating a more general function really pays off. In this case, I created a function that returns a list of all possible coin configurations (sorted by number of coins). Once I had that, I just needed to return the first solution and add the number of coins.
Try it online!
Haskell
I have to admit I fell for the naive solution until I read davidmmooneys comment. The problem is to find the least amount of coins, not to use as many of the largest denomination coin as possible.
My initial solution was as follows:
Notice how the last test outputs 4. using this approach we find 25 + 5 + 5 + 5 = 40, although this is true, 20 + 20 = 40 is a better solution as it uses 2 coins.
The following is an improved solution based on the fact that you can divide the problem into sub problems that are also valid. for example if 20 + 20 + 1 + 1 = 42 is the best solution for 42 then 20 + 20 = 40 and 1 + 1 = 2 must be the best solution for 40 and 2 respectively. I start with the fact that you need 0 coins to get an amount of 0, then calculate the best amount for each amount between 0 and the input.