860. Lemonade Change

860. Lemonade Change

1. 题目

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
Explanation:
From the first 3 customers, we collect three $5 bills in order.
From the fourth customer, we collect a $10 bill and give back a $5.
From the fifth customer, we give a $10 bill and a $5 bill.
Since all customers got correct change, we output true.
Note:
0 <= bills.length <= 10000
bills[i] will be either 5, 10, or 20.

2. 题目分析
题目要求是,老板一开始没有零钱,一瓶柠檬汁5美元,客户只会支付5、10、20美元的现金,然后老板需要通过收取到前面客户支付的现金去给新客户找零钱,判断老板是否能够完全找零钱。有三种情况:

  • 如果客户支付的是5元,则不需要找零钱;
  • 如果客户支付的是10元,则需要找5元零钱;
  • 如果客户支付的是20元,则需要找15元零钱,而15元可以通过一张10元的和一张5元的组成,也可以通过三张5元的组成。我是采用先使用一张10元的和一张5元,因为先使用10元的,可以尽量留下5元的,方便给10元的找零钱;

3. 解题思路
开始是使用hashmap存储5,10,20的现金数量,然后判断使用哪种现金进行找零钱,然后扣掉相应的零钱数量。但最后发现运算效率很低,超过6.8%的用户,,,,后面一想,可以直接用三个int变量存储三个现金的数量,然后再想想,因为只要用5元的和10元进行找零钱,所以可以只存储5元和10元的数量,不需要考虑20元的数量。

4. 代码实现(java)

package com.algorithm.leetcode.greedy;

import java.util.HashMap;

/**
 * Created by 凌 on 2019/1/23.
 * 注释:860. Lemonade Change
 */
public class LemonadeChange {
    public boolean lemonadeChange(int[] bills) {
        if(bills == null || bills.length == 0){
            return true;
        }
        int change=0;
        int fiveNum = 0;//5美元的数量
        int tenNum = 0;//10美元的数量
        for(int i=0;i<bills.length;i++){
            change = bills[i] - 5;
            switch (bills[i]){
                case 5:
                    fiveNum ++;break;
                case 10:
                    if (fiveNum > 0){
                        fiveNum--;
                        tenNum++;
                    }else {
                        return false;
                    }
                    break;
                case 20:
                    //优先使用10元硬币,因为,如果有剩下5元的方便后面找零钱
                    if (tenNum > 0 && fiveNum > 0){
                        tenNum--;
                        fiveNum--;
                    }else if (fiveNum >= 3){
                        fiveNum -= 3;
                    }else {
                        return false;
                    }
                    break;
            }
        }
        return true;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值