|
| 1 | +/** |
| 2 | + * At a lemonade stand, each lemonade costs $5. |
| 3 | + * |
| 4 | + * Customers are standing in a queue to buy from you, and order one at a time |
| 5 | + * (in the order specified by bills). |
| 6 | + * |
| 7 | + * Each customer will only buy one lemonade and pay with either a $5, $10, or |
| 8 | + * $20 bill. You must provide the correct change to each customer, so that |
| 9 | + * the net transaction is that the customer pays $5. |
| 10 | + * |
| 11 | + * Note that you don't have any change in hand at first. |
| 12 | + * |
| 13 | + * Return true if and only if you can provide every customer with correct change. |
| 14 | + * |
| 15 | + * Example 1: |
| 16 | + * Input: [5,5,5,10,20] |
| 17 | + * Output: true |
| 18 | + * Explanation: |
| 19 | + * From the first 3 customers, we collect three $5 bills in order. |
| 20 | + * From the fourth customer, we collect a $10 bill and give back a $5. |
| 21 | + * From the fifth customer, we give a $10 bill and a $5 bill. |
| 22 | + * Since all customers got correct change, we output true. |
| 23 | + * |
| 24 | + * Example 2: |
| 25 | + * Input: [5,5,10] |
| 26 | + * Output: true |
| 27 | + * |
| 28 | + * Example 3: |
| 29 | + * Input: [10,10] |
| 30 | + * Output: false |
| 31 | + * |
| 32 | + * Example 4: |
| 33 | + * Input: [5,5,10,10,20] |
| 34 | + * Output: false |
| 35 | + * Explanation: |
| 36 | + * From the first two customers in order, we collect two $5 bills. |
| 37 | + * For the next two customers in order, we collect a $10 bill and give back a $5 bill. |
| 38 | + * For the last customer, we can't give change of $15 back because we only have two $10 bills. |
| 39 | + * Since not every customer received correct change, the answer is false. |
| 40 | + * |
| 41 | + * Note: |
| 42 | + * 0 <= bills.length <= 10000 |
| 43 | + * bills[i] will be either 5, 10, or 20. |
| 44 | + */ |
| 45 | + |
| 46 | +publicclassLemonadeChange860 { |
| 47 | +publicbooleanlemonadeChange(int[]bills) { |
| 48 | +intfive =0,ten =0; |
| 49 | +for (intbill:bills) { |
| 50 | +if (bill ==5) { |
| 51 | +five++; |
| 52 | + }elseif (bill ==10) { |
| 53 | +if (five ==0)returnfalse; |
| 54 | +five--; |
| 55 | +ten++; |
| 56 | + }else { |
| 57 | +if (five >0 &&ten >0) { |
| 58 | +five--; |
| 59 | +ten--; |
| 60 | + }elseif (five >=3) { |
| 61 | +five -=3; |
| 62 | + }else { |
| 63 | +returnfalse; |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | +returntrue; |
| 69 | + } |
| 70 | +} |