Suppose you are running a lemonade stand. Customers are standing in a queue to buy from you and order one cup of lemonade each. Each lemonade costs $5. Customers can only pay with a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction leaves you with appropriate denominations for future customers. Return true
if you can provide every customer with correct change, and false
otherwise.
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 the customers got 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 two customers, we collect two $5 bills.
For the next two customers, we collect a $10 bill and give back a $5 bill.
For the last customer, we cannot 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.
true
because there are no customers, so no change needs to be made.bills
array?
bills
array:
false
.false
.true
.public class LemonadeChange {
public boolean lemonadeChange(int[] bills) {
int fiveCount = 0, tenCount = 0;
for (int bill : bills) {
if (bill == 5) {
fiveCount++;
} else if (bill == 10) {
if (fiveCount == 0) {
return false;
}
fiveCount--;
tenCount++;
} else { // bill == 20
if (tenCount > 0 && fiveCount > 0) {
tenCount--;
fiveCount--;
} else if (fiveCount >= 3) {
fiveCount -= 3;
} else {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
LemonadeChange lc = new LemonadeChange();
int[] bills1 = {5, 5, 5, 10, 20};
System.out.println(lc.lemonadeChange(bills1)); // true
int[] bills2 = {5, 5, 10};
System.out.println(lc.lemonadeChange(bills2)); // true
int[] bills3 = {10, 10};
System.out.println(lc.lemonadeChange(bills3)); // false
int[] bills4 = {5, 5, 10, 10, 20};
System.out.println(lc.lemonadeChange(bills4)); // false
}
}
The time complexity of the solution is O(n)
where n
is the number of elements in the bills
array. This is because we are iterating through each bill exactly once and performing constant time operations within the loop.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?