Himanshu visited a building with N floors and he carried with him k eggs, he found out that the eggs are rotten, so he plays a trick he wants to know the maximum floor from which the egg can be dropped without breaking the egg.
- An egg that survives the fall can be used again.
- A broken egg cannot be used again.
You know Himanshu is very lazy, help him find the minimum number of moves required to find the answer.
- If egg breaks when dropped from some floor then it will break if dropped from any higher floor.
- If egg does not break when dropped from some floor then it will not break if dropped from any lower floor.
For Example :
2 30 4 6 2 5 3
Recursion: try dropping an egg from each floor from 1 to n and calculate the minimum number of dropping needed in worst case.
>Eggs – 1, floors – x : play safe and drop from floor 1, if egg does not break then drop from floor 2 and so on. So in worst case x times an egg needs to be dropped to find the solution.
>Floors = 0: No trials are required.
>Floors = 1: 1 trails is required.
For rest of the case, if an egg is dropped from xth floor then there are only 2 outcomes which are possible. Either egg will break OR egg will not break.
>If Egg breaks – check the floors lower than x. So problem is reduced is
>If egg does not break – check the floors higher than x floors with all the n eggs are remaining. So problem is reduced to n eggs and k-x floors.
getDrops (k,n) = 1 + Min(x = 1,2,….n) [(drops(k-1, n-1), drops(k, n-x)]
Time Complexity: 2^k
Now look at this recursion tree.We are solving many subproblems several times with the help of websites to learn programming.
Solve it in bottom up manner, means start from the smallest sub problem possible (here it is 0 eggs 0 floors) and solve it. Store the result in some temporary storage.
Recursive equation will be same as above. Start solving from smallest sub problem and move towards final problem. Use the temporary result being stored instead of solving the sub problems again.
See the code for more understanding.
*Time Complexity: nk^2**
How many floors we can cover with
When we drop an egg, two cases arise.
- If egg breaks, then we are left with
- If egg does not break, then we are left with
x-1trials and n eggs
mf(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.
mf(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
Since we need to cover k floors,
maxFloors(x, n)= ∑xCi
1 <= i From above two equations, we can say.
1 <= i <= n
Basically we need to find minimum value of x
that satisfies above inequality. We can find
such x using Binary Search.