-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathEggDrop.cpp
32 lines (26 loc) · 894 Bytes
/
EggDrop.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
// Problem: https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/
#include <bits/stdc++.h>
using namespace std;
class EggDrop {
public:
int twoEggDrop(int n) {
memset(dp, -1, sizeof(dp));
return eggDropUtil(2, n);
}
private:
int eggDropUtil(int eggs, int floors) {
if (floors <= 1) return floors;
if (floors == 2) return 2;
if (eggs == 1) return floors;
if (dp[eggs][floors] != -1) return dp[eggs][floors];
int result = INT_MAX;
for (int i = 1; i <= floors; ++i) {
result = min(result, 1 +
max(eggDropUtil(eggs - 1, i - 1), // Egg breaks on Ith floor.
eggDropUtil(eggs, floors - i))); // Egg doesn't break on the Ith floor.
}
dp[eggs][floors] = result;
return dp[eggs][floors];
}
int dp[3][1001];
};