[LeetCode] Building Boxes

1739. Building Boxes

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 x is placed on top of the box y, then each side of the four vertical sides of the box y must either be adjacent to another box or to a wall.

Given an integer n, return the minimum possible number of boxes touching the floor.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
long long helper(int n) {
if(n == 0) return 0;
int res = 1;
while(res * (res + 1) / 2 < n) res++;
return res;
}
public:
int minimumBoxes(int n) {
long long res = 1, sum = 0, cnt = 1;
while(sum + res <= n) {
sum += res;
res = res + ++cnt;
}
return (res - cnt) + helper(n-sum);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/16/PS/LeetCode/building-boxes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.