AlgoDaily Solution

1var assert = require('assert');
2
3function coinChange(coins, amount) {
4  // Each memo[i] is the least amount of coins
5  // that can make the value equal to the index value.
6  const memo = Array(amount + 1).fill(Infinity);
7  memo[0] = 0;
8
9  for (let i = 1; i <= amount; i++) {
10    for (const coin of coins) {
11      if (i - coin >= 0) {
12        memo[i] = Math.min(memo[i], memo[i - coin] + 1);
13      }
14    }
15  }
16  return memo[amount] === Infinity ? -1 : memo[amount];
17}
18
19try {
20  assert.equal(coinChange([2, 3, 5], 11), 3);
21
22  console.log('PASSED: ' + 'First Test: coinChange([2, 3, 5], 11)');
23} catch (err) {
24  console.log(err);
25}
26
27try {
28  assert.equal(coinChange([2, 3, 5, 7], 17), 3);
29
30  console.log('PASSED: ' + 'Second Test: coinChange([2, 3, 5, 7]');
31} catch (err) {
32  console.log(err);
33}
34
35try {
36  assert.equal(coinChange([2, 3, 7], 15), 4);
37
38  console.log('PASSED: ' + 'Third Test: coinChange([2, 3, 7], 15)');
39} catch (err) {
40  console.log(err);
41}
42
43try {
44  assert.equal(coinChange([3, 5], 7), -1);
45
46  console.log('PASSED: ' + 'Fourth Test: coinChange([3, 5], 7)');
47} catch (err) {
48  console.log(err);
49}
50
51try {
52  assert.equal(coinChange([2, 3, 5], 1), -1);
53
54  console.log('PASSED: ' + 'Fifth Test: coinChange([2, 3, 5]');
55} catch (err) {
56  console.log(err);
57}

Community Solutions

Community solutions are only available for premium users.

Access all course materials today

The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.

Returning members can login to stop seeing this.

JAVASCRIPT
OUTPUT
Results will appear here.