Leetcode 860: Lemonade Change

grid47
grid47
Exploring patterns and algorithms
Aug 13, 2024 7 min read

You are managing a lemonade stand where each lemonade costs $5. Customers are standing in line to buy one lemonade each, paying with either a $5, $10, or $20 bill. Your task is to determine if you can provide the correct change to every customer as they arrive in line. At the start, you have no change, and you must provide each customer with the appropriate change for their bill.
Problem
Approach
Steps
Complexity
Input: You are given an integer array, bills, where each element represents the bill a customer uses to pay for their lemonade. The bills array contains values of either 5, 10, or 20, corresponding to the bill used by each customer.
Example: Input: bills = [5, 5, 10, 5, 20]
Constraints:
• 1 <= bills.length <= 10^5
• bills[i] is either 5, 10, or 20.
Output: Return true if it is possible to provide the correct change for every customer in line. Otherwise, return false.
Example: Output: true
Constraints:
Goal: The goal is to check if the change can be provided to each customer in the order they arrive.
Steps:
• Step 1: Iterate through the array of bills and for each customer, check the bill they provide.
• Step 2: If the customer pays with a $5 bill, increment the count of $5 bills.
• Step 3: If the customer pays with a $10 bill, ensure that you have at least one $5 bill to give change. If so, give the change and update the count of $5 and $10 bills.
• Step 4: If the customer pays with a $20 bill, check if you have one $10 bill and one $5 bill to give $15 in change. If not, check if you have at least three $5 bills to provide $15 in change.
• Step 5: If you cannot provide the correct change at any point, return false.
Goal: The bills array must meet the following constraints:
Steps:
• The length of the bills array is between 1 and 10^5.
• Each bill in the array is either a $5, $10, or $20 bill.
Assumptions:
• There will always be at least one customer in the queue.
• The customers will always pay with one of the allowed bills: $5, $10, or $20.
Input: Input: bills = [5, 5, 10, 5, 20]
Explanation: In this case, the first two customers pay with $5 bills. The third customer pays with a $10 bill, and we can give $5 change. The fourth customer pays with a $5 bill, and the fifth customer pays with a $20 bill. We give them $10 change using one $10 bill and one $5 bill, and the correct change is provided for all customers.

Input: Input: bills = [5, 5, 10, 10, 20]
Explanation: Here, the first two customers pay with $5 bills. The next two customers pay with $10 bills, but we can't provide the correct change for the fourth customer because we only have one $5 bill, not enough to give $5 change. Therefore, the answer is false.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus