codewars算法题(找零钱)

来源:互联网 发布:网络红人丁可 编辑:程序博客网 时间:2024/05/22 08:21

此题为codewars中的一个算法题

The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single 10050 or 25 dollars bill. A "Avengers" ticket costs 25 dollars.

Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this line.

Can Vasya sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?

Return YES, if Vasya can sell a ticket to each person and give the change. Otherwise return NO.

1 题目的主要意思是:

           卖票员现在没钱,买票的人排成了一队,票价为25元/张,按排队顺序卖票,算法实现的功能是判断队伍中的一个人是否能买到票,能则返回“YES”,反之返回“NO”

2主要思路:

         若买票的人持25元则买到;

        若买票人持50元:

                                     (1)如果卖票员此时身上有25元零钱则出票成功

                                     (2)否则失败

        若买票人持100元:

                                      (1)如果卖票员即有50元,又有25元,出票成功(优先出50元的)

                                      (2)或如果卖票员持25*3,则出票成功

                                      (3)否则失败

3 代码实现

 def tickets(people):
    n25=n50=n100=0
    for n in people:
        if n==25:
            n25+=1
        elif n==50 and n25>0:
            n25-=1;n50+=1
        elif n==100 and n50>0 and n25>0:
            n25-=1;n50-=1;n100+=1
        elif n==100 and n50==0 and n25>3:
            n25-=3;n100+=1
        else:
            return "NO"
    return"YES"

持续更新~~~~~

原创粉丝点击