Skip to content

Commit 3bc46a6

Browse files
committed
Created super_egg_drop.cpp
1 parent af97c8e commit 3bc46a6

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// SUPER EGG DROP
2+
// ===============
3+
4+
// You are given k identical eggs and you have access to a building with n floors labeled from 1 to n.
5+
6+
// 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.
7+
8+
// 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.
9+
10+
// Return the minimum number of moves that you need to determine with certainty what the value of f is.
11+
12+
13+
14+
// Example 1:
15+
16+
// Input: k = 1, n = 2
17+
// Output: 2
18+
// Explanation:
19+
// Drop the egg from floor 1. If it breaks, we know that f = 0.
20+
// Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1.
21+
// If it does not break, then we know f = 2.
22+
// Hence, we need at minimum 2 moves to determine with certainty what the value of f is.
23+
// Example 2:
24+
25+
// Input: k = 2, n = 6
26+
// Output: 3
27+
// Example 3:
28+
29+
// Input: k = 3, n = 14
30+
// Output: 4
31+
32+
33+
// Constraints:
34+
35+
// 1 <= k <= 100
36+
// 1 <= n <= 104
37+
38+
39+
// Problem Link: https://leetcode.com/problems/super-egg-drop/
40+
41+
42+
class Solution {
43+
public:
44+
int superEggDrop(int k, int n) {
45+
46+
int dp[n+1][k+1];
47+
48+
for(int j=0; j<k+1; j++){
49+
dp[0][j] = 0;
50+
dp[1][j] = 1;
51+
}
52+
53+
for(int i=0; i<n+1; i++){
54+
dp[i][0] = 0;
55+
dp[i][1] = i;
56+
}
57+
58+
for(int j=2; j<k+1; j++){
59+
for(int i=2; i<n+1; i++){
60+
61+
int ans = INT_MAX;
62+
int low = 1;
63+
int high = i;
64+
while(high >= low){
65+
int mid = (high+low)/2;
66+
int up = dp[i-mid][j];
67+
int down = dp[mid-1][j-1];
68+
int temp = max(up, down) +1;
69+
ans = min(ans, temp);
70+
71+
if(up > down)
72+
low = mid+1;
73+
else
74+
high = mid-1;
75+
}
76+
dp[i][j] = ans;
77+
}
78+
}
79+
80+
return dp[n][k];
81+
}
82+
};

0 commit comments

Comments
 (0)