Dynamic Programming – Egg Dropping Problem
Objective: There are n number of eggs and building which has k floors. Write an algorithm to find the minimum number of drops is required to know the floor from which if egg is dropped, it will break.
- One trial is – dropping an egg once from the particular floor.
- If egg does not break after dropping, will be used again.
- 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.
N eggs, k floors
Recursion: try dropping an egg from each floor from 1 to k and calculate the minimum number of dropping needed in worst case.
- Base cases –
- 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 n-1 eggs and x-1 floors.
- 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.
n eggs, k floors getDrops (n, k) – given n eggs and k floor building, minimum of drops to determine the floor from which egg does not break if dropped. getDrops (n, k) = 1 + Min(x = 1,2,….k) [(drops(n-1, k-1), drops(n, k-x)]
(Recursion) Minimum number of drops required in worst case with eggs: 2 and floors: 10 is: 4
Time Complexity: 2k
If we look closely we are solving many sub problems repeatedly.
Dynamic Programming: Bottom-up
- 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: n2
(DP) Minimum number of drops required in worst case with eggs: 2 and floors: 100 is : 14
Top Companies Interview Questions..-
If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.