Skip to content

Commit 9fd9e9b

Browse files
authored
Create building-boxes.cpp
1 parent 88eef57 commit 9fd9e9b

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

C++/building-boxes.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Time: O(1)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int minimumBoxes(int n) {
7+
// find max h s.t. sum(k*(k+1)//2 for k in xrange(1, h+1)) <= n
8+
// => find max h s.t. h*(h+1)*(h+2)//6 <= n
9+
int h = pow(6.0 * n, 1.0 / 3);
10+
if (int64_t(h) * (h + 1) * (h + 2) / 6 > n) {
11+
// (h-1)*h*(h+1) < h^3 <= 6n < h*(h+1)*(h+2) < (h+1)^3
12+
--h;
13+
}
14+
n -= int64_t(h) * (h + 1) * (h + 2) / 6;
15+
int d = ceil((-1 + sqrt(1 + 8 * n)) / 2); // find min d s.t. d*(d+1)//2 >= n
16+
return h * (h + 1) / 2 + d;
17+
}
18+
};

0 commit comments

Comments
 (0)