forked from algorithm008-class01/algorithm008-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPLemonadeChange.java
More file actions
95 lines (91 loc) · 2.76 KB
/
Copy pathPLemonadeChange.java
File metadata and controls
95 lines (91 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//在柠檬水摊上,每一杯柠檬水的售价为 5 美元。
//
// 顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。
//
// 每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。
//
// 注意,一开始你手头没有任何零钱。
//
// 如果你能给每位顾客正确找零,返回 true ,否则返回 false 。
//
// 示例 1:
//
// 输入:[5,5,5,10,20]
//输出:true
//解释:
//前 3 位顾客那里,我们按顺序收取 3 张 5 美元的钞票。
//第 4 位顾客那里,我们收取一张 10 美元的钞票,并返还 5 美元。
//第 5 位顾客那里,我们找还一张 10 美元的钞票和一张 5 美元的钞票。
//由于所有客户都得到了正确的找零,所以我们输出 true。
//
//
// 示例 2:
//
// 输入:[5,5,10]
//输出:true
//
//
// 示例 3:
//
// 输入:[10,10]
//输出:false
//
//
// 示例 4:
//
// 输入:[5,5,10,10,20]
//输出:false
//解释:
//前 2 位顾客那里,我们按顺序收取 2 张 5 美元的钞票。
//对于接下来的 2 位顾客,我们收取一张 10 美元的钞票,然后返还 5 美元。
//对于最后一位顾客,我们无法退回 15 美元,因为我们现在只有两张 10 美元的钞票。
//由于不是每位顾客都得到了正确的找零,所以答案是 false。
//
//
//
//
// 提示:
//
//
// 0 <= bills.length <= 10000
// bills[i] 不是 5 就是 10 或是 20
//
// Related Topics 贪心算法
package leetcode.editor.cn;
//Java:柠檬水找零
public class PLemonadeChange{
public static void main(String[] args) {
Solution solution = new PLemonadeChange().new Solution();
// TO TEST
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean lemonadeChange(int[] bills) {
if( bills[0] != 5) return false;
int fiveCount = 1;
int tenCount = 0;
int twoTyCount = 0;
for(int i=1;i< bills.length; i++) {
if (bills[i] == 5) {
fiveCount++;
continue;
}
else if (bills[i] == 10) {
if( --fiveCount < 0) return false;
tenCount++;
} else if (bills[i] == 20){
if (tenCount>0) {
tenCount--;
if ( --fiveCount < 0) return false;
} else {
fiveCount -= 3;
if( fiveCount < 0) return false;
}
twoTyCount++;
}
}
return true;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}