[LeetCode] Egg Drop With 2 Eggs and N Floors

1884. Egg Drop With 2 Eggs and N Floors

You are given two identical eggs and you have access to a building with n floors labeled from 1 to n.

You know that there exists a floor f where 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.

In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.

Return the minimum number of moves that you need to determine with certainty what the value of f is.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int twoEggDrop(int n,int k = 2) {
vector<vector<int>> dp(n+1,vector<int>(k+1));
for(int i = 1; i <= n; i++) dp[i][1] = i;
for(int f = 1; f <= n; f++) {
for(int e = 2; e <= k; e++) {
dp[f][e] = n + 1;
for(int i = 1; i <= f; i++)
dp[f][e] = min(dp[f][e], 1 + max(dp[i-1][e-1], dp[f-i][e]));
}
}

return dp[n][k];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/22/PS/LeetCode/egg-drop-with-2-eggs-and-n-floors/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.