# Leetcode 860. Lemonade Change 練習 > Difficulty : `Easy` > `Java` `演算法Algorithm` > 撰寫人[name=KVJK_2125] [time=SAT, May 18, 2024 22:30] ## 題目 ### 說明 Description EN:<br>At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or `$20` bill. You must provide the correct change to each customer so that the net transaction is that the customer pays `$5`. Note that you do not have any change in hand at first. Given an integer array `bills` where `bills[i]` is the bill the `ith` customer pays, return `true` if you can provide every customer with the correct change, or `false` otherwise. 繁中:<br>在檸檬水攤上,每一杯檸檬水的售價為`5`美元。顧客排隊購買你的產品,(按帳單`bills`支付的順序)一次購買一杯。 <br>每位顧客只買一杯檸檬水,然後向你付`5`美元、`10`美元或`20`美元。你必須給每個顧客正確找零,這意味著淨交易是每位顧客向你支付`5`美元。 <br> 注意,一開始你手邊沒有任何零錢。 <br> 給你一個整數陣列`bills`,其中`bills[i]`是第`i`位顧客付的帳,如果你能給每位顧客正確找零,回傳`truw`,否則回傳`false`。 ### 範例 Example Example 1: > Input: bills = [5,5,5,10,20] Output: true Explanation: From the first 3 customers, we collect three $5 bills in order. From the fourth customer, we collect a $10 bill and give back a $5. From the fifth customer, we give a $10 bill and a $5 bill. Since all customers got correct change, we output true. Example 2: >Input: bills = [5,5,10,10,20] Output: false Explanation: From the first two customers in order, we collect two $5 bills. For the next two customers in order, we collect a $10 bill and give back a $5 bill. For the last customer, we can not give the change of $15 back because we only have two $10 bills. Since not every customer received the correct change, the answer is false. ### 限制條件 Constraints - `1 <= bills.length <= 105` - `bills[i]` is either `5`, `10`, or `20`. ## 解題 ### 思路 Intuition/Approach - Step1.<br> 建立變數`coin5`和`coin10`紀錄手中擁有的零錢,初始設定為0 - Step2.<br> 建立for迴圈,設定為`bills`長度的次數 - Step3.<br> 若收到5元,則`coin5++`;<br><br>若收到10元,則確認是否能夠找零:<br>- 是:`coin5--`且`coin10++`<br>- 否:不可找零,傳回`false`<br><br>若收到20元,則確認是否能夠找零:<br>- 有5元及10元:`coin5--`且`coin10--`<br>- 只有5元,且5元最少有三個:`coin5-=3`<br>- 以上情況皆非:不可找零,傳回false<br><br> 若全部順利找零,則最終回傳`true`。 ### 程式碼 Code(加註解) ```clink= class Solution { public boolean lemonadeChange(int[] bills) { //建立變數紀錄手上有的零錢 int coin5 = 0,coin10 = 0; //開始交易(?) for(int i : bills) { //如果是5,則5元+1 if(i == 5) coin5 ++; //如果是10,則確認有無零錢 else if(i == 10) { //可找錢的情況 if(coin5 > 0) { coin5--; coin10++; } //不可找錢 else return false; } //因為只有5、10、20,所以這邊是20 else { //可找錢的情況:5元跟10元都有,則找錢 if(coin5 > 0 && coin10 > 0) { coin5 --; coin10 --; } //可找錢的情況:沒有10元,5元有兩個以上 else if(coin5 > 2) { coin5 -= 3; } //不可找錢的情況 else return false; } } return true; } } ```