-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEggDropProblem.cpp
More file actions
79 lines (62 loc) · 1.8 KB
/
EggDropProblem.cpp
File metadata and controls
79 lines (62 loc) · 1.8 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//
// main.cpp
// EggDropProblem
// https://leetcode.com/problems/super-egg-drop/
// Created by Madhumitha Raghu on 5/21/21.
//
#include <iostream>
#include <unordered_map>
typedef std::pair<int, int> pair;
struct pair_hash
{
template <class T1, class T2>
std::size_t operator() (const std::pair<T1, T2> &pair) const {
return std::hash<T1>()(pair.first) ^ std::hash<T2>()(pair.second);
}
};
class EggDrop {
public:
EggDrop(int e, int f)
: nEggs(e), nFloors(f) {
}
int solve() {
return drop(nFloors, nEggs);
}
private:
int drop(int n, int k) {
if (map.find({n,k}) != map.end())
return map[{n,k}];
// 1 floor or 0 floors
if (n == 1 || n == 0) {
return n;
}
// 1 egg
if (k == 1) {
return n;
}
int min = std::numeric_limits<int>::max();
// Start from floor 1 to current floor
// Throw the egg and every floor and there are 2 possibilities:
// a) Egg breaks and we explore the lower floors
// b) Egg does not break and we explore the higher floors
// At any given floor, we need to pick the worst case number of
// trials. However, we want to minimize this across different iterations
for (int x = 1; x <= n; ++x) {
min = std::min(std::max(drop(x - 1, k - 1), drop(n - x, k)), min);
}
// We add 1 because exploring a floor exhausts one trial
map[{n,k}] = min + 1;
return map[{n,k}];
}
private:
int nEggs;
int nFloors;
std::unordered_map<std::pair<int,int>,int,pair_hash> map;
};
int main()
{
EggDrop obj(2, 100);
int res = obj.solve();
std::cout << res << std::endl;
return 0;
}