Leetcode: Drop Eggs — Python

Leetcode: Drop Eggs — Python

Question

You are given K eggs, and you have access to a building with N floors from 1 to N.

Each egg is identical in function, and if an egg breaks, you cannot drop it again.

You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor higher than F will break, and any egg dropped at or below floor F will not break.

Each move, you may take an egg (if you have an unbroken one) and drop it from any floor X (with 1 <= X <= N).

Your goal is to know with certainty what the value of F is.

What is the minimum number of moves that you need to know with certainty what F is, regardless of the initial value of F?

Answer

  1. method one (create a 2D list)
class Solution:
    def superEggDrop(self, K, N):
        """
        :type K: int--eggs
        :type N: int--floors
        :rtype: int
        """
        state = [[0]*(N+1) for i in range(K+1)]
        
        #boader
        #k = 0 or k =1
        for i in range(N+1):
            state[0][i] = 0
            state[1][i] = i
            
        #N = 0 or N =1
        for i in range(K+1):
            state[i][0] = 0
            state[i][1] = 1
        
        #other situations
        for egg in range(2,K+1):
            for floor in range(2, N+1):
                result = 1000000
                for drop in range(1,floor+1):
                    #egg break
                    brek = state[egg-1][drop-1]
                    #egg not break
                    unbrek = state[egg][floor-drop]
                    result = min(max(brek, unbrek) + 1, result)
                state[egg][floor] = result
        
        return state[K][N]
  1. method two
class Solution(object):
    def superEggDrop(self, K, N):
        def f(x):
            ans = 0
            r = 1
            for i in range(1, K+1):
                r *= x-i+1
                r //= i
                ans += r
                if ans >= N: 
                	break
            return ans

        lo, hi = 1, N
        while lo < hi:
            mi = (lo + hi) // 2
            if f(mi) < N:
                lo = mi + 1
            else:
                hi = mi
        return lo

note

method one is Time Limit Exceeded…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值