Summing up to amount with fewest coins in JavaScript


Problem

We are required to write a JavaScript function that takes in arr, arr, as the first argument. This array basically specifies the different types of coin denominations we have.

The second argument to the function is a number, amount, which specifies the amount we want to add up to. Our function should simply return the minimum number of coins required to add up to that amount.

If we can, in no way, reach amount, we should return -1.

For example, if the input to the function is −

const arr = [1, 2, 5];
const amount = 17;

Then the output should be −

const output = 4;

Output Explanation:

Because the amount can be achieved using 3 coins of 5 and 1 coin of 2.

Example

The code for this will be −

const arr = [1, 2, 5];
const amount = 17;
const minCoins = (arr = [], amount = 1) => {
   const changes = [];
   changes[0] = 0;
   while(changes.length <= amount){
      let change = Math.pow(2, 31) - 1;
      for (let i = 0; i < arr.length; i++) {
         if (changes.length - arr[i] < 0){
            continue;
         };
         change = Math.min(change, 1 + changes[changes.length - arr[i]]);
      };
      changes.push(change);
   };
   return changes[amount] == Math.pow(2, 31) - 1 ? -1 : changes[amount];
};
console.log(minCoins(arr, amount));

Output

And the output in the console will be −

4

Updated on: 20-Mar-2021

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements