712390. Lemonade Change
Lemonade Change
Slug: lemonade-change
Difficulty: Medium
Id: 712390
Topic Tags: Arrays, Greedy, Data Structures, Algorithms
Company Tags: None
Summary
The Lemonade Change problem is about a simple vending machine that sells lemonades for $5 each. The goal is to determine the minimum number of lemons and sugar required to make change for all possible amounts of money that can be given by customers. This problem involves arrays, greedy algorithms, and data structures.
Detailed Explanation
To solve this problem, we need to first understand how a vending machine makes change. When a customer gives a certain amount of money, the vending machine needs to return some combination of lemons (1 dollar each) and sugar packets (5 dollars each). The goal is to find the minimum number of lemons and sugar required to make this change.
Here's a step-by-step breakdown of the solution:
- Initialize variables to keep track of the number of lemons and sugar.
- Iterate over all possible amounts of money that can be given by customers (from 0 to 100).
- For each amount, calculate how many times the cost of lemonade ($5) fits into the given amount. This will give us the maximum number of lemons that can be used to make change.
- Calculate how much change is left after using all the lemons. This will be the amount of sugar required to make change.
- Update the count of lemons and sugar accordingly.
Here's a simple diagram to illustrate this process:
+---------------+
| Amount |
+---------------+
|
v
+---------------+
| Leemons |
| (1$ each) |
+---------------+
|
v
+---------------+
| Sugar |
| (5$ each) |
+---------------+
Time complexity: O(n), where n is the maximum amount of money given by customers. Space complexity: O(1), as we only use a few variables to keep track of the count.
Optimized Solutions
Java
public class LemonadeChange {
public static int lemonadeChange(int[] bills) {
int lemons = 0;
int sugar = 0;
for (int bill : bills) {
if (bill == 5) {
if (sugar >= 1) {
sugar -= 1;
} else if (lemons >= 3) {
lemons -= 3;
sugar += 1;
} else {
return 0;
}
} else if (bill == 10) {
if (sugar >= 1 && lemons >= 1) {
sugar -= 1;
lemons -= 1;
} else if (lemons >= 3) {
lemons -= 3;
} else {
return 0;
}
} else if (bill == 1) {
lemons += bill;
}
}
return lemons / 3 + sugar / 5;
}
}