[Coding Made Simple] Egg Dropping
Given some number of floors and some number of eggs, what is the minimum number of attempts it will take to find out from which floor egg will break.
Dynamic Programming solution.
Say we have a maximum of n floors and a total of m eggs. We are currently attempting to drop an egg from the kth floor.In order to get the optimal solution, we need to calculate what would happen if we dropped an egg from every floor (1 through to n) and recursively calculate the minimum number of droppings needed in the worst case. We're looking for the floor that gives the minimum solution to the worst case.
If we dropp an egg from floor k, one of two events happens:
1. the egg breaks, our problem is reduced to check k - 1 floors with m - 1 eggs.
2. the egg does not break, our problem is reduced to check n - k floors with m eggs.
Remember we need to mimimize the number of drops in the worst case, so we take the higher (max) of these two situations, and select the floor which yields the minimum number of drops.
The code to solve this is fairly easy to write recursively, but suffers from a common problem that occurs with recursive solutions in which the same sub-problems are evaluated again, and again, and again, dragging performance to a grind for anything other than trivial solutions. To get around this, we need to keep track of values already computed so that we don't have to repeat the calculation.
1 public class EggDrop { 2 public int minDrops(int floors, int eggs) { 3 int[][] minDrops = new int[eggs + 1][floors + 1]; 4 for(int j = 0; j <= floors; j++) { 5 minDrops[0][j] = 0; 6 } 7 for(int i = 0; i <= eggs; i++) { 8 minDrops[i][0] = 0; 9 } 10 for(int j = 1; j <= floors; j++) { 11 minDrops[1][j] = j; 12 } 13 for(int i = 2; i <= eggs; i++) { 14 for(int j = 1; j <= floors; j++) { 15 int min = Integer.MAX_VALUE; 16 for(int k = 1; k <= j; k++) { 17 min = Math.min(min, Math.max(minDrops[i - 1][k - 1], minDrops[i][j - k])); 18 } 19 minDrops[i][j] = 1 + min; 20 } 21 } 22 return minDrops[eggs][floors]; 23 } 24 }