Question
Given an input amount of change x, write a function to determine the minimum number of coins required to make that amount of change.
eg. (using American coins)
1 2 3 4 |
change(1) = 1 change(3) = 3 change(7) = 3 change(32) = 4 |
Once you think that you’ve solved the problem, click below to see the solution.
As always, remember that practicing coding interview questions is as much about how you practice as the question itself. Make sure that you give the question a solid go before skipping to the solution. Ideally if you have time, write out the solution first by hand and then only type it into your computer to verify your work once you've verified it manually. To learn more about how to practice, check out this blog post.
Solution
How was that problem? You can check out the solution in the video below.
Here is the source code for the solution shown in the video:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
public int change(int x, int[] coins) { if (x == 0) return 0; int min = x; for (int coin : coins) { if (x - coin >= 0) { int c = change(x - coin, coins); if (min > c + 1) min = c + 1; } } return min; } public int changeDynamic(int x, int[] coins) { int[] cache = new int[x]; for (int i = 1; i < x; i++) { cache[i] = -1; } return changeDynamic(x, coins, cache); } public int changeDynamic(int x, int[] coins, int[] cache) { if (x == 0) return 0; int min = x; for (int coin : coins) { if (x - coin >= 0) { int c; if (cache[x - coin] >= 0) c = cache[x - coin]; else { c = changeDynamic(x - coin, coins, cache); cache[x - coin] = c; } if (min > c + 1) min = c + 1; } } return min; } |
Did you get the right answer to this coding interview question? Please share your thoughts in the comments below.