Skip to content

Commit b7a0db3

Browse files
authored
Create 0860_Lemonade_Change.cpp
1 parent cb9b26c commit b7a0db3

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

Cpp/0860_Lemonade_Change.cpp

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/*
2+
At a lemonade stand, each lemonade costs $5.
3+
4+
Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills).
5+
6+
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.
7+
8+
Note that you don't have any change in hand at first.
9+
10+
Return true if and only if you can provide every customer with correct change.
11+
12+
13+
14+
Example 1:
15+
16+
Input: [5,5,5,10,20]
17+
Output: true
18+
Explanation:
19+
From the first 3 customers, we collect three $5 bills in order.
20+
From the fourth customer, we collect a $10 bill and give back a $5.
21+
From the fifth customer, we give a $10 bill and a $5 bill.
22+
Since all customers got correct change, we output true.
23+
24+
Example 2:
25+
26+
Input: [5,5,10]
27+
Output: true
28+
29+
Example 3:
30+
31+
Input: [10,10]
32+
Output: false
33+
34+
Example 4:
35+
36+
Input: [5,5,10,10,20]
37+
Output: false
38+
Explanation:
39+
From the first two customers in order, we collect two $5 bills.
40+
For the next two customers in order, we collect a $10 bill and give back a $5 bill.
41+
For the last customer, we can't give change of $15 back because we only have two $10 bills.
42+
Since not every customer received correct change, the answer is false.
43+
44+
45+
Note:
46+
47+
0 <= bills.length <= 10000
48+
bills[i] will be either 5, 10, or 20.
49+
*/
50+
51+
class Solution {
52+
public:
53+
bool lemonadeChange(vector<int>& bills) {
54+
vector<int> change(2,0);
55+
for (int i = 0; i < bills.size(); ++i) {
56+
if (bills[i] == 5) {
57+
change[0]++;
58+
}
59+
else if (bills[i] == 10) {
60+
if (change[0] == 0) {
61+
return false;
62+
}
63+
64+
change[0]--;
65+
change[1]++;
66+
}
67+
else {
68+
if (change[1] > 0 && change[0] > 0) {
69+
change[0]--;
70+
change[1]--;
71+
}
72+
else if (change[0] > 3) {
73+
change[0] -= 3;
74+
}
75+
else {
76+
return false;
77+
}
78+
}
79+
}
80+
81+
return true;
82+
}
83+
};

0 commit comments

Comments
 (0)