You are given
K
eggs, and you have access to a building withN
floors from1
toN
.Each egg is identical in function, and if an egg breaks, you cannot drop it again.
You know that there exists a floor
F
with0 <= F <= N
such that any egg dropped at a floor higher thanF
will break, and any egg dropped at or below floorF
will not break.Each move, you may take an egg (if you have an unbroken one) and drop it from any floor
X
(with1 <= 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 ofF
?
Example 1:
Input: K = 1, N = 2 Output: 2 Explanation: Drop the egg from floor 1. If it breaks, we know with certainty that F = 0. Otherwise, drop the egg from floor 2. If it breaks, we know with certainty that F = 1. If it didn‘t break, then we know with certainty F = 2. Hence, we needed 2 moves in the worst case to know what F is with certainty.
Example 2:
Input: K = 2, N = 6 Output: 3
Example 3:
Input: K = 3, N = 14 Output: 4
Note:
1 <= K <= 100
1 <= N <= 10000
Approach #1: DP. [C++][TLE][O(K*N^2)]
class Solution { public: int superEggDrop(int K, int N) { int c = 0; vector<vector<int>> dp(K+1, vector<int>(N+1, 0)); for (int i = 1; i <= N; ++i) dp[1][i] = i; for (int i = 2; i <= K; ++i) { for (int j = 1; j <= N; ++j) { dp[i][j] = INT_MAX; for (int k = 1; k <= j; ++k) { c = 1 + max(dp[i-1][k-1], dp[i][j-k]); if (c < dp[i][j]) dp[i][j] = c; } } } return dp[K][N]; } };
Approach #2: DP. [Java]
class Solution { public int superEggDrop(int K, int N) { int[][] dp = new int[N+1][K+1]; int m = 0; while (dp[m][K] < N) { ++m; for (int k = 1; k <= K; ++k) dp[m][k] = dp[m-1][k-1] + dp[m-1][k] + 1; } return m; } }
Analysis:
Firstly, if we have K eggs and s steps to detect a buliding with Q(k, s) floors.
Secondly, we use 1 egg and 1 step to detect one floor,
if egg break, we can use (k-1) eggs and (s-1) to detect with Q(k-1, s-1),
if egg isn‘t broken, we can use k eggs and (s-1) step to detech with Q(k, s-1),
So, Q(k,s) = 1 + Q(k, s-1) + Q(k-1, s-1);
dp[i] is max floors we can use i eggs and s step to detect.
Reference:
https://leetcode.com/problems/super-egg-drop/discuss/159508/easy-to-understand