Summing up to amount with fewest coins in JavaScript

The coin change problem is a classic dynamic programming challenge where we need to find the minimum number of coins required to make a specific amount. If the amount cannot be achieved with the given coin denominations, we return -1.

Problem Statement

We need to write a JavaScript function that takes two parameters:

  • arr: An array containing different coin denominations
  • amount: The target amount we want to achieve

The function should return the minimum number of coins needed to sum up to the target amount.

Example Input and Output

const arr = [1, 2, 5];
const amount = 17;
console.log("Coins:", arr);
console.log("Target amount:", amount);
Coins: [ 1, 2, 5 ]
Target amount: 17

The expected output is 4 because we can achieve 17 using 3 coins of value 5 and 1 coin of value 2 (5 + 5 + 5 + 2 = 17).

Dynamic Programming Solution

We use dynamic programming to build up solutions for smaller amounts and use them to find the solution for the target amount.

const minCoins = (arr = [], amount = 0) => {
    // Create array to store minimum coins needed for each amount
    const dp = new Array(amount + 1).fill(Infinity);
    dp[0] = 0; // 0 coins needed for amount 0
    
    // For each amount from 1 to target amount
    for (let i = 1; i 

4

How It Works

The algorithm works as follows:

  1. Initialize a DP array where dp[i] represents the minimum coins needed for amount i
  2. Set dp[0] = 0 since no coins are needed for amount 0
  3. For each amount from 1 to target, try using each available coin
  4. Update the minimum coins needed by comparing current value with using the coin

Testing with Different Cases

const testCases = [
    { coins: [1, 2, 5], amount: 17 },
    { coins: [2, 5], amount: 3 },      // Cannot be achieved
    { coins: [1, 3, 4], amount: 6 },
    { coins: [1], amount: 0 }
];

testCases.forEach((test, index) => {
    const result = minCoins(test.coins, test.amount);
    console.log(`Test ${index + 1}: coins=[${test.coins}], amount=${test.amount} ? ${result}`);
});
Test 1: coins=[1,2,5], amount=17 ? 4
Test 2: coins=[2,5], amount=3 ? -1
Test 3: coins=[1,3,4], amount=6 ? 2
Test 4: coins=[1], amount=0 ? 0

Time and Space Complexity

Aspect Complexity Description
Time O(amount × coins.length) We iterate through each amount and each coin
Space O(amount) DP array stores solutions for all amounts up to target

Conclusion

The coin change problem demonstrates the power of dynamic programming for optimization problems. By building solutions bottom-up, we efficiently find the minimum number of coins needed for any target amount.

Updated on: 2026-03-15T23:19:00+05:30

226 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements