Leetcode 860. Lemonade Change

本文探讨了LeetCode上的经典问题“柠檬水找零”,详细解释了如何在顾客购买柠檬水时正确找零,确保交易顺利进行。通过贪心策略和计数器技巧,文章提供了一种高效解决此问题的方法,确保卖家在没有初始零钱的情况下,仍能满足所有顾客的找零需求。

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;
    }
};
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值