-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathBuilding Boxes.cpp
45 lines (41 loc) · 1.03 KB
/
Building Boxes.cpp
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
// Runtime: 2 ms (Top 64.56%) | Memory: 6.40 MB (Top 55.7%)
class Solution {
private:
int getLayerSize(int x){
return x * (x+1) / 2;
}
int getCubeSize(int x){
long d = static_cast<long>(x);
long sz = (d * (d+1) * (d+2)) / 6;
return static_cast<int>(sz);
}
public:
int minimumBoxes(int n) {
// First Binary Search
int l(0), r(2000), m;
while(l <= r)
{
m = (l+r)/2;
int sz = getCubeSize(m);
if(sz <= n)
l = m + 1;
else
r = m - 1;
}
int aSideOfPyramid = r;
int rest = n - getCubeSize(aSideOfPyramid);
// Second Binary Search
l=0,r=2000;
while(l <= r)
{
m = (l+r)/2;
int sz = getLayerSize(m);
if(sz < rest)
l = m + 1;
else
r = m - 1;
}
int addedFloorCubic = l;
return getLayerSize(aSideOfPyramid) + addedFloorCubic;
}
};