1861. Building Boxes
My accepted C++ solution to LeetCode problem 1861, Building Boxes, running in 0ms.
- Difficulty: Hard
- C++
- Runtime 0ms
- Memory 7.9MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
C++
Accepted on LeetCode — runtime 0ms, memory 7.9MB, accepted 2025-12-27.
class Solution {
public:
int minimumBoxes(int n) {
// Find largest triangular pyramid that fits
// Total boxes in pyramid of height h = h*(h+1)*(h+2)/6
// Floor boxes = h*(h+1)/2
long long total = 0, floor_boxes = 0, h = 0;
// Build complete pyramid
while (total + (h + 1) * (h + 2) / 2 <= n) {
h++;
floor_boxes = h * (h + 1) / 2;
total += h * (h + 1) / 2;
}
// Add additional floor boxes one by one
long long extra = 0, add = 0;
while (total < n) {
add++;
extra += add;
total += add;
}
return floor_boxes + add;
}
};