Skip to content

Commit ec5888c

Browse files
committed
提交柠檬水找零作业
1 parent f84c789 commit ec5888c

1 file changed

Lines changed: 68 additions & 0 deletions

File tree

Week04/LemonadeChange.java

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
public class LemonadeChange {
5+
6+
private static final int RECEIVE = 5;
7+
private static final int LEVEL1 = 5;
8+
private static final int LEVEL2 = 10;
9+
private static final int LEVEL3 = 20;
10+
11+
public boolean lemonadeChange(int[] bills) {
12+
if (bills[0] > RECEIVE) {
13+
return false;
14+
}
15+
Map<Integer, Integer> map = new HashMap<>(bills.length);
16+
boolean flag = true;
17+
for (int bill : bills) {
18+
int count = map.getOrDefault(bill, 0);
19+
map.put(bill, count + 1);
20+
int change = bill - RECEIVE;
21+
int div = change / LEVEL1;
22+
if (div == 0) {
23+
continue;
24+
}
25+
if (div == 1) {
26+
if (map.getOrDefault(change, 0) == 0) {
27+
return false;
28+
}
29+
int count0 = map.getOrDefault(change, 0) - 1;
30+
map.put(change, count0);
31+
} else {
32+
int change1 = LEVEL2;
33+
int change2 = LEVEL1;
34+
boolean hasChange1 = map.getOrDefault(change1, 0) >= 1;
35+
boolean hasChange2 = map.getOrDefault(change2, 0) >= 1;
36+
if (!hasChange2) {
37+
return false;
38+
}
39+
if (!hasChange1) {
40+
boolean hasChange3 = map.getOrDefault(change2, 0) >= (LEVEL3 - LEVEL1) / LEVEL1;
41+
if (!hasChange3) {
42+
return false;
43+
}
44+
int count3 = map.getOrDefault(change2, 0) - ((LEVEL3 - LEVEL1) / LEVEL1);
45+
if (count3 > 0) {
46+
map.put(change2, count3);
47+
} else {
48+
map.remove(change2);
49+
}
50+
continue;
51+
}
52+
int count1 = map.getOrDefault(change1, 0) - 1;
53+
if (count1 > 0) {
54+
map.put(change1, count1);
55+
} else {
56+
map.remove(change1);
57+
}
58+
int count2 = map.getOrDefault(change2, 0) - 1;
59+
if (count2 > 0) {
60+
map.put(change2, count2);
61+
} else {
62+
map.remove(change2);
63+
}
64+
}
65+
}
66+
return flag;
67+
}
68+
}

0 commit comments

Comments
 (0)