Sponsored
Sponsored
This approach involves using a greedy strategy where we maintain counters for $5 and $10 bills. When a $5 bill is received, simply increase the count. For a $10 bill, check if you have a $5 bill to give as change. For a $20 bill, prefer giving one $10 and one $5 bill as change if available, otherwise give three $5 bills.
Time Complexity: O(n), where n is the length of the bills array.
Space Complexity: O(1), since only a fixed amount of additional space is used for counters.
1class Solution:
2 def lemonadeChange(self, bills: List[int]) -> bool:
3 five, ten = 0, 0
4 for bill in bills:
5 if bill == 5:
6 five += 1
7 elif bill == 10:
8 if five == 0:
9 return False
10 five -= 1
11 ten += 1
12 else:
13 if ten > 0 and five > 0:
14 ten -= 1
15 five -= 1
16 elif five >= 3:
17 five -= 3
18 else:
19 return False
20 return True
The Python solution uses variables to track the count of $5 and $10 bills. It processes each bill, updating counts and checking if a transaction can be completed. The function returns false if a customer cannot receive the correct change.
This approach focuses on prioritizing the use of $10 bills when giving change to customers with $20 bills. By simulating the process, we ensure that change is handled with a clear order of preference, utilizing available higher denominations first.
Time Complexity: O(n), where n is the size of the bills array.
Space Complexity: O(1), using only fixed space for counters.
1 public bool LemonadeChange(int[] bills) {
int five = 0, ten = 0;
foreach (int bill in bills) {
if (bill == 5) five++;
else if (bill == 10) {
if (five == 0) return false;
five--; ten++;
} else {
if (ten > 0 && five > 0) {
ten--; five--;
} else if (five >= 3) {
five -= 3;
} else {
return false;
}
}
}
return true;
}
}
This C# solution tracks the quantity of bills in hand, preferring to give $10 as part of change if it simplifies future transactions, ensuring a smooth customer experience.