Building Boxes Problem
Description
LeetCode Problem 1739.
You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes:
- You can place the boxes anywhere on the floor.
- If box
xis placed on top of the boxy, then each side of the four vertical sides of the boxymust either be adjacent to another box or to a wall.
Given an integer n, return the minimum possible number of boxes touching the floor.
Example 1:

Input: n = 3
Output: 3
Explanation: The figure above is for the placement of the three boxes.
These boxes are placed in the corner of the room, where the corner is on the left side.
Example 2:

Input: n = 4
Output: 3
Explanation: The figure above is for the placement of the four boxes.
These boxes are placed in the corner of the room, where the corner is on the left side.
Example 3:

Input: n = 10
Output: 6
Explanation: The figure above is for the placement of the ten boxes.
These boxes are placed in the corner of the room, where the corner is on the back side.
Constraints:
1 <= n <= 10^9
Solution
Approach: Staircase in the Corner
To touch the floor as little as possible, stack the boxes in a staircase against the corner of the two walls. A fully built staircase of k layers, counted from the top, holds 1, 1 + 2, ..., 1 + 2 + ... + k boxes per layer, so its floor has k(k+1)/2 boxes.
- Find the largest
ksuch that a full staircase withklayers holds at mostnboxes. The floor of that staircase isk(k+1)/2boxes, and the staircase itself usessboxes in total. - The
n - sboxes that are left are placed on the floor next to the staircase. The first extra floor box supports one box, the second supports two, and so on, so adding floor box numberiraises the capacity byi. Add floor boxes one at a time until the capacity reachesn.
The answer is the floor of the full staircase plus the number of extra floor boxes.
Complexity: O(n1/3) time for the first loop (the staircase total grows like k3) and O(sqrt(n)) for the second, so O(sqrt(n)) overall, with O(1) extra space.
class Solution:
def minimumBoxes(self, n: int) -> int:
s, k = 0, 1
while s + k * (k + 1) // 2 <= n:
s += k * (k + 1) // 2
k += 1
k -= 1
ans = k * (k + 1) // 2
k = 1
while s < n:
ans += 1
s += k
k += 1
return ans