Given n eggs and k floors, find the minimum number of trials needed in worst case to find the floor below which all floors are safe. A floor is safe if dropping an egg from it does not break the egg. Please see n eggs and k floors. for complete statements
Input : n = 2, k = 10 Output : 4 We first try from 4-th floor. Two cases arise, (1) If egg breaks, we have one egg left so we need three more trials. (2) If egg does not break, we try next from 7-th floor. Again two cases arise. We can notice that if we choose 4th floor as first floor, 7-th as next floor and 9 as next of next floor, we never exceed more than 4 trials. Input : n = 2. k = 100 Output : 14
We have discussed the problem for 2 eggs and k floors. We have also discussed a dynamic programming solution to find the solution. The dynamic programming solution is based on below recursive nature of the problem. Let us look at the discussed recursive formula from a different perspective.
How many floors we can cover with x trials?
When we drop an egg, two cases arise.
- If egg breaks, then we are left with x-1 trials and n-1 eggs.
- If egg does not break, then we are left with x-1 trials and n eggs
Let maxFloors(x, n) be the maximum number of floors that we can cover with x trials and n eggs. From above two cases, we can write. maxFloors(x, n) = maxFloors(x-1, n-1) + maxFloors(x-1, n) + 1 For all x >= 1 and n >= 1 Base cases : We can't cover any floor with 0 trials or 0 eggs maxFloors(0, n) = 0 maxFloors(x, 0) = 0 Since we need to cover k floors, maxFloors(x, n) >= k ----------(1) The above recurrence simplifies to following, Refer this for proof. maxFloors(x, n) = ∑xCi 1 <= i <= n ----------(2) Here C represents Binomial Coefficient. From above two equations, we can say. ∑xCj >= k 1 <= i <= n Basically we need to find minimum value of x that satisfies above inequality. We can find such x using Binary Search.
Time Complexity : O(n Log k)
- Egg Dropping Puzzle with 2 Eggs and K Floors
- Binomial Coefficient | DP-9
- Sum of product of r and rth Binomial Coefficient (r * nCr)
- Maximum binomial coefficient term value
- Space and time efficient Binomial Coefficient
- Egg Dropping Puzzle | DP-11
- Puzzle | Set 35 (2 Eggs and 100 Floors)
- Meta Binary Search | One-Sided Binary Search
- Linear Search vs Binary Search
- Interpolation search vs Binary search
- Binary Search in PHP
- Binary Search
- Uniform Binary Search
- Binary Search a String
- The Ubiquitous Binary Search | Set 1
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.