Vending machine bug

Report a typo

When people buy an item in a vending machine, sometimes they need to be given change. Your colleague released an updated version of ATM software and went on vacation. Unfortunately, after an update, one of the functions for the change-giving process started working incorrectly: it returns the wrong message in all cases.

Check the code and fix a bug. Change only one code line.

Sample Input 1:

1, 5, 10, 25
48

Sample Output 1:

Minimum number of coins needed to make 48 cents: 6
Write a program in Java 25
import java.util.Arrays;

class CashChanging {
public static void printCoinsAmount(int[] coins, int amount) {
int minCoins = CashChanging.getMinimumCoinsAmount(coins, amount);

if (minCoins == -1) {
System.out.println("It is not possible to make " + amount + " cents using the given denominations.");
} else {
System.out.println("Minimum number of coins needed to make " + amount + " cents: " + minCoins);
}
}

private static int getMinimumCoinsAmount(int[] coins, int initialAmount) {
Arrays.sort(coins);
int count = 0;
int index = coins.length - 1;

int amount = initialAmount;
while (amount > 0 && index >= 0) {
if (coins[index] <= amount) {
int numCoins = amount / coins[index];
count += numCoins;
amount -= numCoins * coins[index];
}
index--;
}
// !!! DO NOT CHANGE THE CODE ABOVE !!!
return -1;
}
}

Create a free account to access the full topic