Senior
44
/** * Interfață pentru interacțiunea cu hardware-ul bancomatului. */ interface Hardware { /** * Returnează un array cu numărul de bancnote pentru denumirile 50, 100, 500, 1000, 5000. * Metoda funcționează lent și produce zgomot. * * @return array în care fiecare element corespunde numărului de bancnote pentru o anumită denumire. * De exemplu, [10, 20, 30, 40, 50] înseamnă: * - 10 bancnote de 50 de ruble * - 20 bancnote de 100 de ruble * - 30 bancnote de 500 de ruble * - 40 bancnote de 1000 de ruble * - 50 bancnote de 5000 de ruble */ int[] getBillsCounts(); /** * Încarcă în cutia de ieșire bancnotele indicate. * * @param billsCounts array cu numărul de bancnote pentru denumirile [50, 100, 500, 1000, 5000]. * De exemplu, [0, 1, 0, 2, 0] înseamnă: * - 0 bancnote de 50 * - 1 bancnotă de 100 * - 0 bancnote de 500 * - 2 bancnote de 1000 * - 0 bancnote de 5000 */ void giveBills(int[] billsCounts); } /** * Clasa pentru implementarea logicii bancomatului. * Aici trebuie scris codul */ class MyATM { /** * Hardware-ul bancomatului. */ Hardware hardware; public boolean withdraw(int amount) { int[] counts = hardware.getBillsCounts(); int[] nom = {50, 100, 500, 1000, 5000}; int[] toGive = new int[5]; for (int i = 4; i >= 0; i--) { int needed = amount / nom[i]; int use = Math.min(needed, counts[i]); toGive[i] = use; amount -= use * nom[i]; } if (amount != 0) { return false; } hardware.giveBills(toGive); return true; } }
Companiile au fost întrebate
Răspuns de la AI
sobes.tech AI
В представленном коде метод withdraw пытается выдать запрошенную сумму, используя купюры доступных номиналов, начиная с самых крупных. Однако такой жадный алгоритм не всегда находит решение, даже если оно существует.
Чтобы улучшить логику, можно реализовать динамическое программирование или перебор с возвратом (backtracking), чтобы найти комбинацию купюр, которая точно даст нужную сумму, учитывая ограничения по количеству купюр каждого номинала.
Пример улучшенного подхода с использованием рекурсии и мемоизации (псевдокод):
boolean tryWithdraw(int amount, int[] counts, int[] nom, int index, int[] toGive) {
if (amount == 0) return true;
if (index < 0 || amount < 0) return false;
for (int i = 0; i <= counts[index]; i++) {
toGive[index] = i;
if (tryWithdraw(amount - i * nom[index], counts, nom, index - 1, toGive)) {
return true;
}
}
toGive[index] = 0;
return false;
}
public boolean withdraw(int amount) {
int[] counts = hardware.getBillsCounts();
int[] nom = {50, 100, 500, 1000, 5000};
int[] toGive = new int[5];
if (!tryWithdraw(amount, counts, nom, nom.length - 1, toGive)) {
return false;
}
hardware.giveBills(toGive);
return true;
}
Такой подход гарантирует, что если сумма может быть выдана, то метод её найдет, несмотря на ограничения по количеству купюр.