Greedy

An algorithmic pattern that uses the 'best looking' path at each step. This may miss an optimal solution for some problems.


Example

The fewest number of coins totaling a specific value can be greedily computed for USD denominations.

function fewestCoins(amount, coinValues) {
  // assumes coin values are in decreasing order
  let result = 0;

  for (const coinValue of coinValues) {
    result += Math.floor(amount / coinValue);
    amount %= coinValue;
  }

  return result;
}
fewestCoins(55, [25, 10, 5, 1]);
3

External Resources