860. Lemonade Change
I recently solved the "Lemonade Change" problem on LeetCode and wanted to share my approach. This problem requires us to determine if we can provide correct change to each customer in a queue, given they may pay with $5, $10, or $20 bills, while the price of lemonade is always $5.
Problem Summary:
- Objective: Ensure each customer receives the correct change.
- Constraints: You can only provide change with the bills you have received from previous customers.
Approach:
I used a greedy algorithm to solve this problem, focusing on always giving change in the largest denominations first to maximize the availability of smaller bills for future transactions.
Code Explanation: (javascript)
/**
* @param {number[]} bills
* @return {boolean}
*/
var lemonadeChange = function(bills) {
let count5 = 0;
let count10 = 0;
for(let i = 0; i < bills.length; i++){
if(bills[i] == 5){
count5++;
}else if(bills[i] == 10){
count5--;
count10++;
}else{
if(count10 >= 1){
count10--;
count5--;
}else{
count5 -= 3;
}
}
if(count5 < 0){
return false;
}
}
return true;
};
Code Explanation:(java)
class Solution {
public boolean lemonadeChange(int[] bills) {
int count5 = 0;
int count10 = 0;
for(int i = 0; i < bills.length; i++){
if(bills[i] == 5){
count5++;
}else if(bills[i] == 10){
count5--;
count10++;
}else{
if(count10 >= 1){
count10--;
count5--;
}else{
count5 -= 3;
}
}
if(count5 < 0){
return false;
}
}
return true;
}
}
Comments
Post a Comment