MCPcopy Create free account
hub / github.com/algorithmzuo/videocode / Code03_AppleMinBags

Class Code03_AppleMinBags

src/videocode/Code03_AppleMinBags.java:3–77  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1package videocode;
2
3public class Code03_AppleMinBags {
4
5 public static int minBag(int apple) {
6 if (apple < 0) {
7 return -1;
8 }
9 if (apple == 0) {
10 return 0;
11 }
12 // max 决定用多少个8号袋 100 / 8 = 12 11 10 ... 0
13 for (int max = (apple / 8); max >= 0; max--) {
14 // max 个 8号袋的时候,max * 8, 6号袋剩下的苹果数 = apple - max * 8
15 int rest = apple - (max * 8);
16 if (rest % 6 == 0) {
17 return max + rest / 6;
18 }
19 }
20 return -1;
21 }
22
23 // O(1)
24 public static int test(int apple) {
25 if(apple < 0) {
26 return -1;
27 }
28 if(apple == 0) {
29 return 0;
30 }
31 if(apple < 18) {
32 if(apple == 6 || apple == 8) {
33 return 1;
34 }else if(apple == 12 || apple == 14 || apple == 16) {
35 return 2;
36 }else {
37 return -1;
38 }
39 }
40 // apple >= 18
41 // apple 第几组?
42 // (apple - 18) / 8
43 // 18 ~ 25 0组 奇数 -1 偶数 3
44 // 26 ~ 33 1组 奇数 -1 偶数 4
45 // 34 ~ 41 2组 奇数 -1 偶数 5
46 // X >= 18 -> X属于i组, X是奇数 -1 偶数 i + 3
47 return apple % 2 == 0 ? ((apple - 18) / 8 + 3) : -1;
48 }
49
50 public static int minBagAwesome(int apple) {
51 if (apple < 0 || (apple & 1) != 0) {
52 return -1;
53 }
54 if (apple == 0) {
55 return 0;
56 }
57 if (apple < 18) {
58 if (apple == 6 || apple == 8) {
59 return 1;
60 } else if (apple == 12 || apple == 14 || apple == 16) {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected