-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path42_EggDropping_memoization_BinarySearch.cpp
45 lines (39 loc) · 1.48 KB
/
42_EggDropping_memoization_BinarySearch.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
public:
int Solve(int eggs, int floors, vector<vector<int>>& t) {
if (t[eggs][floors] != -1) {
return t[eggs][floors];
}
if (eggs == 0) {
return 0;
}
if (eggs == 1 || floors == 0 || floors == 1) {
return floors;
}
int mn = INT_MAX;
int low = 0, high = floors, temp = 0;
while(low <= high){
int mid = (low + high)/2;
/* representing both the choices with memo
First one, if the egg will break, no. of eggs will decreased and we have to
down from that floor.
Second one, if the egg will not break, no. of eggs will not decreased and we
have to go above form that floor. */
int breaks = Solve(eggs-1, mid-1, t); // left
int not_breaks = Solve(eggs, floors-mid, t); // right
temp = 1 + max(breaks, not_breaks);
//since we need more temp value in worst case, so need to go above
if(breaks < not_breaks) { // left < right
low = mid+1;
} else {
high = mid-1; // move to the downward
}
mn = min(mn, temp); // minimum number of attempts
}
return t[eggs][floors] = mn;
}
int superEggDrop(int k, int n) {
vector<vector<int>> t(k+1, vector<int> (n+1, -1));
return Solve(k, n, t);
}
};