I am writing an algorithm that should return "yes" if a list of customers are to pay for a movie and receive their change (money) considering the the clerk starts receiving payments with an empty cashier pause, meaning he cant give change from the start. The movie costs 25 $ so if a customer has 50 $ the clerk has to refuse unless he has already received 25 $ from previous customer so is able to use that as change for the next customer.
I have such algorithm
public static String Tickets(int[] peopleInLine) {
int sumOfMoneyWithCashier = 0;
int cost = 25;
for (int i = 0; i < peopleInLine.length; i++) {
if (peopleInLine[i] == cost) {
sumOfMoneyWithCashier += peopleInLine[i];
if (peopleInLine[i + 1] == cost) {
sumOfMoneyWithCashier += cost;
} else if (peopleInLine[i + 1] > cost) {
int change = peopleInLine[i + 1] - cost;
if (sumOfMoneyWithCashier >= change) {
sumOfMoneyWithCashier -= change;
} else {
System.out.println("no");
return "NO";
}
}
} else if (peopleInLine[i] > cost) {
int change = peopleInLine[i] - cost;
if (sumOfMoneyWithCashier >= change) {
sumOfMoneyWithCashier -= change;
} else {
System.out.println("no");
return "NO";
}
}
}
System.out.println("YES");
return "YES";
}
Now it works but not perfect , how can i improve this code so it check handles most of the scenario, ignore case where customer comes with less than 25. customers must come with multiples of 25 between range of {25, 50, 100} How can i make this code better is the question , i would appreciate an example code and explanation basically
Line.Tickets(new int[] {25, 25, 50}) // => YES
Line.Tickets(new int[]{25, 100}) // => NO. Vasya will not have enough money to give change to 100 dollars
Line.Tickets(new int[] {25, 25, 50, 50, 100}) // => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)