Skip to content

Commit bccf316

Browse files
Egg Drop Problem
1 parent d2fadb5 commit bccf316

1 file changed

Lines changed: 63 additions & 0 deletions

File tree

EggDropProblem.cpp

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
// A utility function to get
5+
// maximum of two integers
6+
int max(int a, int b)
7+
{
8+
return (a > b) ? a : b;
9+
}
10+
11+
/* Function to get minimum
12+
number of trials needed in worst
13+
case with n eggs and k floors */
14+
int eggDrop(int n, int k)
15+
{
16+
/* A 2D table where entry
17+
eggFloor[i][j] will represent
18+
minimum number of trials needed for
19+
i eggs and j floors. */
20+
int eggFloor[n + 1][k + 1];
21+
int res;
22+
int i, j, x;
23+
24+
// We need one trial for one floor and 0
25+
// trials for 0 floors
26+
for (i = 1; i <= n; i++) {
27+
eggFloor[i][1] = 1;
28+
eggFloor[i][0] = 0;
29+
}
30+
31+
// We always need j trials for one egg
32+
// and j floors.
33+
for (j = 1; j <= k; j++)
34+
eggFloor[1][j] = j;
35+
36+
// Fill rest of the entries in table using
37+
// optimal substructure property
38+
for (i = 2; i <= n; i++) {
39+
for (j = 2; j <= k; j++) {
40+
eggFloor[i][j] = INT_MAX;
41+
for (x = 1; x <= j; x++) {
42+
res = 1 + max(
43+
eggFloor[i - 1][x - 1],
44+
eggFloor[i][j - x]);
45+
if (res < eggFloor[i][j])
46+
eggFloor[i][j] = res;
47+
}
48+
}
49+
}
50+
51+
// eggFloor[n][k] holds the result
52+
return eggFloor[n][k];
53+
}
54+
55+
56+
int main()
57+
{
58+
int n = 2, k = 36;
59+
cout << "\nMinimum number of trials "
60+
"in worst case with " << n<< " eggs and "<< k<<
61+
" floors is "<< eggDrop(n, k);
62+
return 0;
63+
}

0 commit comments

Comments
 (0)