我正在写一个算法,如果一个客户列表要为一部电影付款并收到他们的零钱(钱),那么应该返回“是”,因为职员开始收到付款时会出现一个空的出纳暂停,这意味着他不能从一开始就给出更改。这部电影要花25美元,所以如果一个顾客有50美元,店员必须拒绝,除非他已经收到了前一个顾客的25美元,这样他就可以把它作为下一个顾客的零钱。
我有这样的算法
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";
}
现在它工作了,但并不完美,我如何改进这段代码,使它检查处理大多数场景,忽略客户少于25岁的情况。客户必须在25、50、100_范围内提供25的倍数
我如何才能使这段代码更好是个问题,我希望能有一个示例代码和解释
基本上
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)