LeetCode --- 贪心算法 --- 860. 柠檬水找零

这个和日常数钱一个道理 你肯定是多少张5块的多少张10块的这样来考虑收钱对吧。所以消耗额外的空间少不了了。至于有人用for循环和我用递归其实都一样。至于时间复杂度都最坏就是 o(n)了。

 public bool LemonadeChange(int[] bills)
        {
            if (bills[0] != 5)
                return false;
            var count5 = 0;
            var count10 = 0;
            var index = 0;
            return _LemonadeChange(bills, count5, count10, index);
        }

        private bool _LemonadeChange(int[] bills, int count5, int count10, int index)
        {
            if (index >= bills.Length)
            {
                return true;
            }
            else
            {
                while (index < bills.Length)
                {
                    if (bills[index] == 5)
                    {
                        count5++;
                        index++;
                    }
                    else if (bills[index] == 10)
                    {
                        if (count5 - 1 < 0) return false;
                        count5--;
                        count10++;
                        index++;
                    }
                    else if (bills[index] == 20)
                    {
                        if (count10 > 0 && count5 > 0)
                        {
                            count5--;
                            count10--;
                            index++;
                        }
                        else if (count10 <= 0 && count5 - 3 >= 0)
                        {
                            count5 = count5 - 3;
                            index++;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }

                return _LemonadeChange(bills, count5, count10, index);
            }
        }

递归没有多余计算还是挺快的,内存也还好。以下仅供参考。。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值