- 1
Dinamic programing Challenge JS
pls explain the parts I commented in layman's terms Min change Write a function minChange that takes in an amount and an array of coins. The function should return the minimum number of coins required to create the amount. You may use each coin as many times as necessary. If it is not possible to create the amount, then return -1. test_00: minChange(8, [1, 5, 4, 12]); // -> 2, because 4+4 is the minimum coins possible SOLUTION: https://www.sololearn.com/compiler-playground/c479HsP3Be55
1 ответ
+ 3
This is the interesting part in the code:
let min = Infinity;
for (let coin of coins) {
const numCoins = 1 + _minChange(amount - coin, coins, memo);
min = Math.min(numCoins, min);
}
What happens here, is you have a certain amount of money in your hand, and a variety of coins.
This for loop tries each coin, and calls the same function recursively, with the amount decreased by the value of the coin.
The "1 + ..." part represents the calculation of how many coins have been used already.
If the coin is too big, the base cases at the beginning of the recursion would catch that and return Infinity, so that would not be a meaningful result for the minimum.
If we reach 0 amount, it means the total sum can be expressed by some coins which roll back in the recursive path to (1 + (1 + (1 +... 0)))
The memo variable is needed, to store results which have already been calculated before. for example your program may have determined at some point that the most optimal way to change 13 would be 2 coins. So this result would be used whenever the next time the recursion wants to know this, so instead of recalculating it again, at the cost of a lot of time and memory, the already determined result is used from memo.