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.

 

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 <= 109

思路:二分底边的数目,然后贪心的排布成1...N的方式,多余的依次添加

class Solution(object):
    def minimumBoxes(self, n):
        """
        :type n: int
        :rtype: int
        """
        def ok(bottom):
            lo,hi=0,bottom
            res = bottom
            while lo<=hi:
                mid=(lo+hi)//2
                if mid*(mid+1)//2<=bottom:
                    res=mid
                    lo=mid+1
                else:
                    hi=mid-1
            if res > n:
                return False

            canBuild = 0
            for i in range(1,res+1):
                canBuild += i*(res-i+1)

            left = bottom - res * (1 + res) // 2
            canBuild += left*(1+left)//2
            return canBuild >= n


        lo,hi = 0,n
        res = n
        while lo<=hi:
            mid=(lo+hi)//2
            if ok(mid):
               res=mid
               hi=mid-1
            else:
                lo=mid+1
        return res

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值