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
- 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]
- 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…