Leetcode 860. Lemonade Change
At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills).Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer, so that the net transaction is that the customer pays $5.Note that you don’t have any change in hand at first.Return true if and only if you can provide every customer with correct change.
Example 1:
Input: [5,5,5,10,20]
Output: true
Example 2:
Input: [5,5,10]
Output: true
Example 3:
Input: [10,10]
Output: false
题目大意:
只有5,10,20三种面值货币,每杯柠檬水5块,作为卖家开始时你没有零钱在手。给定一个付款面值序列,判断你是否能够满足整个序列的找零需求。
解题思路:
使用贪心策略,设置两个计数器记录手上面值为5和10的数量,遍历付款序列,如果收入为5,则计数器5加一,如果收入为10,则计数器10加一且计数器5减一,如果收入为20,则优先找零一张5和一张10,如果没有面额10则找零三张面额5。如果计数器之一为负则返回false。时间复杂度为O(n).
代码:
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int five = 0, ten = 0;
for(int i = 0; i < bills.size(); i++)
{
if(bills[i] == 5)
five++;
else if(bills[i] == 10)
{
ten++;
five--;
}
else
if(ten > 0)
{
ten--;
five--;
}
else
five -= 3;
if(five < 0 || ten < 0)
return false;
}
return true;
}
};
本文探讨了LeetCode上的经典问题“柠檬水找零”,详细解释了如何在顾客购买柠檬水时正确找零,确保交易顺利进行。通过贪心策略和计数器技巧,文章提供了一种高效解决此问题的方法,确保卖家在没有初始零钱的情况下,仍能满足所有顾客的找零需求。
462

被折叠的 条评论
为什么被折叠?



