At the lemonade stand, each glass of lemonade sells for $5.
Customers line up to buy your products, (in the order of bills paid) one cup at a time.
Each customer only buys a glass of lemonade, and then pays you $5, $10, or $20. You must give each customer the correct change, which means that the net transaction is that each customer pays you $5.
Note that you don't have any change in hand at the beginning.
If you can give each customer the correct change, return true, otherwise return false.
Example 1:
Input: [5,5,5,10,20]
Output: true
Explanation: From the
first 3 customers, we collect 3 5 USD bills in order.
From the 4th customer, we received a $10 bill and returned $5.
For the fifth customer, we returned a 10 dollar bill and a 5 dollar bill.
Since all customers got the correct change, we output true.
Example 2:
Input: [5,5,10]
Output: true
Example 3:
Input: [10,10]
Output: false
Example 4:
Input: [5,5,10,10,20]
Output: false
Explanation: From the
first 2 customers, we collect two 5 USD bills in order.
For the next 2 customers, we charge a $10 bill and return $5.
For the last customer, we cannot return $15 because we now only have two $10 bills.
Since not every customer gets the correct change, the answer is false.
prompt:
0 <= bills.length <= 10000
bills[i] is either 5 or 10 or 20
public static boolean lemonadeChange(int[] bills) {
Map<Integer, Integer> map=new HashMap<Integer, Integer>();
for(int i=0;i<bills.length;i++) {
if(bills[i]==5) {
map.put(5,map.getOrDefault(5,0)+1);
}else if (bills[i]==10) {
if(map.getOrDefault(5,0)>0) {
map.put(10,map.getOrDefault(10,0)+1);
map.put(5,map.get(5)-1);
}else {
return false;
}
}else {
if(map.getOrDefault(10,0)>0) {
if(map.getOrDefault(5,0)>0) {
map.put(10,map.get(10)-1);
map.put(5,map.get(5)-1);
}else {
return false;
}
}else {
if(map.getOrDefault(5,0)>3) {
map.put(5,map.get(5)-3);
}else {
return false;
}
}
}
}
return true;
}