Sobes.tech
Middle+

There is an ATM with banknotes of a specified denomination. The user selects the amount of money they want to receive. The ATM should dispense the entered amount with the minimum number of banknotes. Write an ATM function. function atm(notes, sum) { } // atm([1, 5, 50, 100], 362) => [100,100,100,50, 5, 5, 1, 1]

sobes.tech AI

Answer from AI

To solve the problem of dispensing the minimum number of banknotes, a greedy algorithm can be used: sort the denominations in descending order and iteratively subtract the largest possible banknotes from the sum.

function atm(notes, sum) {
  notes.sort((a, b) => b - a); // sort in descending order
  const result = [];
  for (const note of notes) {
    while (sum >= note) {
      sum -= note;
      result.push(note);
    }
  }
  if (sum !== 0) {
    // if the sum cannot be dispensed with the given denominations
    return [];
  }
  return result;
}

// Example
console.log(atm([1, 5, 50, 100], 362));
// Output: [100, 100, 100, 50, 5, 5, 1, 1]

This algorithm works correctly if the denominations allow dispensing any amount (for example, if there is a 1-unit banknote). If not, there may be cases where the amount cannot be dispensed.

There is an ATM with banknotes of a specified… - sobes.tech