Skip to content

Commit 10b97df

Browse files
committed
Create lemonade-change.py
1 parent 989d5a9 commit 10b97df

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

Python/lemonade-change.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
# At a lemonade stand, each lemonade costs $5.
5+
#
6+
# Customers are standing in a queue to buy from you,
7+
# and order one at a time (in the order specified by bills).
8+
#
9+
# Each customer will only buy one lemonade and pay with either a $5, $10,
10+
# or $20 bill. You must provide the correct change to each customer,
11+
# so that the net transaction is that the customer pays $5.
12+
#
13+
# Note that you don't have any change in hand at first.
14+
#
15+
# Return true if and only if you can provide every customer
16+
# with correct change.
17+
#
18+
# Example 1:
19+
#
20+
# Input: [5,5,5,10,20]
21+
# Output: true
22+
# Explanation:
23+
# From the first 3 customers, we collect three $5 bills in order.
24+
# From the fourth customer, we collect a $10 bill and give back a $5.
25+
# From the fifth customer, we give a $10 bill and a $5 bill.
26+
# Since all customers got correct change, we output true.
27+
# Example 2:
28+
#
29+
# Input: [5,5,10]
30+
# Output: true
31+
# Example 3:
32+
#
33+
# Input: [10,10]
34+
# Output: false
35+
# Example 4:
36+
#
37+
# Input: [5,5,10,10,20]
38+
# Output: false
39+
# Explanation:
40+
# From the first two customers in order, we collect two $5 bills.
41+
# For the next two customers in order, we collect a $10 bill and
42+
# give back a $5 bill.
43+
# For the last customer, we can't give change of $15 back
44+
# because we only have two $10 bills.
45+
# Since not every customer received correct change, the answer is false.
46+
#
47+
# Note:
48+
# - 0 <= bills.length <= 10000
49+
# - bills[i] will be either 5, 10, or 20.
50+
51+
52+
class Solution(object):
53+
def lemonadeChange(self, bills):
54+
"""
55+
:type bills: List[int]
56+
:rtype: bool
57+
"""
58+
five, ten = 0, 0
59+
for bill in bills:
60+
if bill == 5:
61+
five += 1
62+
elif bill == 10:
63+
if not five:
64+
return False
65+
five -= 1
66+
ten += 1
67+
else:
68+
if ten and five:
69+
ten -= 1
70+
five -= 1
71+
elif five >= 3:
72+
five -= 3
73+
else:
74+
return False
75+
return True

0 commit comments

Comments
 (0)