Guest User

Untitled

a guest
Oct 23rd, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. public class EggDropRecursion {
  2. public int getDrops(int eggs, int floors){
  3. //base case 1:
  4. //if floors = 0 then no drops are required OR floors = 1 then 1 drop is required
  5. if(floors==0 || floors==1)
  6. return floors;
  7.  
  8. //base case 2:
  9. //if only one egg is there then drops = floors
  10. if(eggs==1)
  11. return floors;
  12.  
  13. int minimumDrops=Integer.MAX_VALUE, tempResult;
  14. //check dropping from all the floors 1 to floors and pick the minimum among those.
  15. //for every drop there are 2 scenarios - a) either egg will break b) egg will not break
  16. for (int i = 1; i <=floors ; i++) {
  17. //for the worst case pick the maximum among a) and b)
  18. tempResult = Math.max(getDrops(eggs-1,i-1), getDrops(eggs, floors-i));
  19. minimumDrops = Math.min(tempResult,minimumDrops);
  20. }
  21. return minimumDrops + 1;
  22. }
  23.  
  24. public static void main(String[] args) {
  25. EggDropRecursion eggDropRecursion = new EggDropRecursion();
  26. int eggs = 2;
  27. int floors = 10;
  28. System.out.printf("(Recursion) Minimum number of drops required in worst case with eggs: " + eggs + " and floors:" + floors + " is: " + eggDropRecursion.getDrops(eggs,floors));
  29. }
  30. }
Add Comment
Please, Sign In to add comment