image.png

    1. public class LemonLength {
    2. public static void main(String[] args) {
    3. System.out.println(change(new int[]{5,5,10,20}));
    4. }
    5. private static boolean change(int[] bills) {
    6. // 定义手上五元和十元的个数都是0
    7. int five = 0,ten = 0;
    8. for (int bill : bills) {
    9. if (bill == 5) {
    10. // 顾客是五元,直接收入
    11. five++;
    12. } else if (bill == 10) {
    13. // 顾客是10元
    14. if (five > 0) {
    15. // 有五元,则可以找零
    16. // 五元数量减1
    17. five--;
    18. // 十元数量加1
    19. ten++;
    20. } else {
    21. // 否则不能找零
    22. return false;
    23. }
    24. } else {
    25. // 顾客是20元
    26. if (five > 0 && ten > 0) {
    27. five--;
    28. ten--;
    29. } else if (five > 3) {
    30. five -= 3;
    31. } else {
    32. return false;
    33. }
    34. }
    35. }
    36. return true;
    37. }
    38. }