860. Lemonade Change
1. 题目
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 don’t have any change in hand at first.
Return true if and only if you can provide every customer with correct change.
Example 1:
Input: [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.
Note:
0 <= bills.length <= 10000
bills[i] will be either 5, 10, or 20.
2. 题目分析
题目要求是,老板一开始没有零钱,一瓶柠檬汁5美元,客户只会支付5、10、20美元的现金,然后老板需要通过收取到前面客户支付的现金去给新客户找零钱,判断老板是否能够完全找零钱。有三种情况:
- 如果客户支付的是5元,则不需要找零钱;
- 如果客户支付的是10元,则需要找5元零钱;
- 如果客户支付的是20元,则需要找15元零钱,而15元可以通过一张10元的和一张5元的组成,也可以通过三张5元的组成。我是采用先使用一张10元的和一张5元,因为先使用10元的,可以尽量留下5元的,方便给10元的找零钱;
3. 解题思路
开始是使用hashmap存储5,10,20的现金数量,然后判断使用哪种现金进行找零钱,然后扣掉相应的零钱数量。但最后发现运算效率很低,超过6.8%的用户,,,,后面一想,可以直接用三个int变量存储三个现金的数量,然后再想想,因为只要用5元的和10元进行找零钱,所以可以只存储5元和10元的数量,不需要考虑20元的数量。
4. 代码实现(java)
package com.algorithm.leetcode.greedy;
import java.util.HashMap;
/**
* Created by 凌 on 2019/1/23.
* 注释:860. Lemonade Change
*/
public class LemonadeChange {
public boolean lemonadeChange(int[] bills) {
if(bills == null || bills.length == 0){
return true;
}
int change=0;
int fiveNum = 0;//5美元的数量
int tenNum = 0;//10美元的数量
for(int i=0;i<bills.length;i++){
change = bills[i] - 5;
switch (bills[i]){
case 5:
fiveNum ++;break;
case 10:
if (fiveNum > 0){
fiveNum--;
tenNum++;
}else {
return false;
}
break;
case 20:
//优先使用10元硬币,因为,如果有剩下5元的方便后面找零钱
if (tenNum > 0 && fiveNum > 0){
tenNum--;
fiveNum--;
}else if (fiveNum >= 3){
fiveNum -= 3;
}else {
return false;
}
break;
}
}
return true;
}
}