forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Building Boxes.java
53 lines (44 loc) · 1.3 KB
/
Building Boxes.java
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
class Solution {
static final double ONE_THIRD = 1.0d / 3.0d;
public int minimumBoxes(int n) {
int k = findLargestTetrahedralNotGreaterThan(n);
int used = tetrahedral(k);
int floor = triangular(k);
int unused = (n - used);
if (unused == 0) {
return floor;
}
int r = findSmallestTriangularNotLessThan(unused);
return (floor + r);
}
private final int findLargestTetrahedralNotGreaterThan(int te) {
int a = (int) Math.ceil(Math.pow(product(6, te), ONE_THIRD));
while (tetrahedral(a) > te) {
a--;
}
return a;
}
private final int findSmallestTriangularNotLessThan(int t) {
int a = -1 + (int) Math.floor(Math.sqrt(product(t, 2)));
while (triangular(a) < t) {
a++;
}
return a;
}
private final int tetrahedral(int a) {
return (int) ratio(product(a, a + 1, a + 2), 6);
}
private final int triangular(int a) {
return (int) ratio(product(a, a + 1), 2);
}
private final long product(long... vals) {
long product = 1L;
for (long val : vals) {
product *= val;
}
return product;
}
private final long ratio(long a, long b) {
return (a / b);
}
}