Classic problem of dynamic programming. Solution of problem Two eggs and 100 floor building
Suppose that there is a building with 100 floors. You are given 2 identical eggs. Both eggs are identical. The most interesting property of the eggs is that every egg has it’s own “threshold” floor. Let’s call that floor N. What this means is that the egg will not break when dropped from any floor below floor N, but the egg will definitely break from any floor above floor N, including floor N itself.
The aim is to find out the highest floor from which an egg will not break when dropped out of a window from that floor. If an egg is dropped and does not break, it is undamaged and can be dropped again. However, once an egg is broken, that’s it for that egg.
If an egg breaks when dropped from floor n, then it would also have broken from any floor above that. If an egg survives a fall, then it will survive any fall shorter than that.
The question is: What strategy should you adopt to minimize the number egg drops it takes to find the solution?. (And what is the worst case for the number of drops it will take?)
There are exists multiple possible and good solutions:
First solution is brute force (you start at first floor, drop an egg, check it, increase a floor, repeat …) Time complexity = O(n), and is possible the worst solution, because we probably did not found the best floor.
My solution is binary search (starting in middle, test, on result of test go middle + some value or middle - some value) Time complexity = O(log(n)).