Skip to Content
Learning JavaScript Data Structures and Algorithms - Third Edition
book

Learning JavaScript Data Structures and Algorithms - Third Edition

by Loiane Avancini
April 2018
Beginner to intermediate content levelBeginner to intermediate
426 pages
10h 19m
English
Packt Publishing
Content preview from Learning JavaScript Data Structures and Algorithms - Third Edition

The min-coin change problem

The min-coin change problem can also be resolved with a greedy algorithm. Most of the time, the result is also optimal, but for some denominations, the result will not be optimal.

Let's take a look at the algorithm:

function minCoinChange(coins, amount) {  const change = [];  let total = 0;  for (let i = coins.length; i >= 0; i--) { // {1}    const coin = coins[i];    while (total + coin <= amount) { // {2}      change.push(coin); // {3}      total += coin; // {4}    }  }  return change;}

Note that the greedy version of minCoinChange is much simpler than the DP one. For each coin ({1}, starting from the biggest one to the smallest one), we will add the coin value to total, and total needs to be less than amount ({2}). We will add coin ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning JavaScript Data Structures and Algorithms

Learning JavaScript Data Structures and Algorithms

Loiane Avancini

Publisher Resources

ISBN: 9781788623872Supplemental Content