2

So this is the classic egg drop problem. I just don't get how the recursion works here. How does it reach the end of the function which returns min+1 every time the recursion takes place?

Note that my very conceptual understanding of recursion may be flawed.

/* Function to get minimum number of trials needed in worst 
case with n eggs and k floors */
int eggDrop(int n, int k) 
{ 
// If there are no floors, then no trials needed. OR if there is 
// one floor, one trial needed. 
if (k == 1 || k == 0) 
    return k; 

// We need k trials for one egg and k floors 
if (n == 1) 
    return k; 

int min = INT_MAX, x, res; 

// Consider all droppings from 1st floor to kth floor and 
// return the minimum of these values plus 1. 
for (x = 1; x <= k; x++) 
{ 
    res = max(eggDrop(n-1, x-1), eggDrop(n, k-x)); 
    if (res < min) 
        min = res; 
} 

return min + 1; 
}
  • I runned your method and it runs on infinite loop, the catch is when you call for (x = 1; x <= k; x++) and you make a new recursion from the start `x=1` – Panos K Jul 15 '19 at 12:45

1 Answers1

0

There are several base cases for the recursion, when n == 1, when k == 0, and when k == 1.

Each non-base-case call has quite a few recursive calls. So, for example, if we want to call eggDrop(2, 5), we will return something like the value of

min (
  // **egg breaks**  **egg doesn't break**
  max (eggDrop (1, 0), eggDrop (2, 4) ),
  max (eggDrop (1, 1), eggDrop (2, 3) ),
  max (eggDrop (1, 2), eggDrop (2, 2) ),
  max (eggDrop (1, 3), eggDrop (2, 1) ),
  max (eggDrop (1, 4), eggDrop (2, 0) ),
)

Note that each of these cases moves us toward one of those base cases. In the first column, we have reduced n by 1, and in the second column, we have reduced k by x, where x is a positive integer no bigger than k. And since each recursive call moves us closer to the base case, we will eventually bottom out.

(You could probably prove this formally by showing that on each recursive call n + k is strictly smaller than on its parent. I won't bother here; the intuition should be enough.)

That should explain how the recursion actually works.

But note how many recursive calls we're making: k * (k - 1) / 2. That means that this recursive version is not likely to be a very performant solution. Hence this problem is generally solved with dynamic programming techniques.

Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103