Assume that we have m eggs, and n drops are allowed. Let us represent the height of the tallest building by g (m, n), for which we can find a solution with these constraints.
g (m, n) = g(m – 1, n – 1) + g (m, n – 1) (n > 0)
g (m, 0) = 1.
This is because if we drop the first egg from the g(m – 1, n – 1)-th step, if it breaks, we still have
(m – 1) eggs and (n – 1) steps, which are enough to detect in a building of height up to g (m – 1, n – 1).
On the other hand, if it does not break, we have m eggs and (n – 1) steps, which can give us extra
g (m, n – 1) height to be able to detect.
For fixed n, the expression of g(m, n) can be calculated explicitly., e.g..
g (2, n) = n * (n + 1)/2, (n >= 3 )
Explanation
n + (n-1) + (n-2) + (n-3) + (n-4) + … + 1 >= 100
n (n+1) / 2 >= 100
3 Eggs
h(3,m) = (m-1)m/2 +1 + (m-2)(m-1)/2+1 + … = SUM (1/2)j^2 – (1/2)j +1 for j from 1 to m and
we get (1/12)m(m+1)(2m+1) – (1/4)m(m+1) + m = (1/6)(m^3 -m) + m = (1/6)(m-1)m(m+1) + m.
(1/6)(m-1)m(m+1) + m < 100 which gives m =9
So 9 is enough.
CODE
When we drop an egg from a floor x, there can be two cases (1) The egg breaks (2) The egg doesn’t break.
1) If the egg breaks after dropping from xth floor, then we only need to check for floors lower than x with remaining eggs; so the problem reduces to x-1 floors and n-1 eggs
2) If the egg doesn’t break after dropping from the xth floor, then we only need to check for floors higher than x; so the problem reduces to k-x floors and n eggs.
/* Function to get minimum number of trails needed in worst
case with n eggs and k floors */
int eggDrop(int n, int k)
{
// If there are no floors, then no trials needed. OR if there is
// one floor, one trial needed.
if (k == 1 || k == 0)
return k;
// We need k trials for one egg and k floors
if (n == 1)
return k;
int min = INT_MAX, x, res;
// Consider all droppings from 1st floor to kth floor and
// return the minimum of these values plus 1.
for (x = 1; x <= k; x++)
{
res = max(eggDrop(n-1, x-1), eggDrop(n, k-x));
if (res < min)
min = res;
}
return min + 1;
}