Super Egg Drop Recursive To Optimization

772
Aug 18, 2021
Aug 18, 2021

Do upvote if you like
Question:https://leetcode.com/problems/super-egg-drop/
Underlying Concept
Before going to the question let's understand the concept that will be used.
Let's suppose there are 3 employees A,B,C in a company. For the same work assigned, each employee has an average of finishing work in 10 days. The manager wants to assign an urgent work that needs to be done in 7 seven days.
Who do you think will be assigned the work ?
image
Answer:
image Yes !! that's correct C is our answer.
The idea is whenever we want to decided with certainty for an event we always look at the worst case possible. In this case we see that worst cases in which the employees finish the work is 15,16,13 respectively. Now we can choose the best out of these work that is 13 which is the minimum days required to finish the work.

The concept of choosing the BEST FROM THE WORST when we want to guarantee for an event will be used in our original problem.
So we are given some floors and we have to determine the critical floor in minimum moves. Critical floor is defined as the floor above which if we drop the egg it breaks.
image
Now we have a choice to throw the egg from 1,2,3....n floor.
Each floor has two option
image

The concept to understand is choosing the floor is in our hand and egg breaking is our luck. So whenever we have to make a decision for our luck with certainty we have to consider luck not to be in our favor. Each floor gives two answers and for every floor we choose the maximum answer using the same concept from the example of employees. In order to be certain of the event we consider the worst possibility of all. In this case is the maximum moves whichever side takes is the worst possibility.
Expanding the knowledge for a single floor we do this for every floor. Now, from the answers that each floor return choose the minimum one.
image

CORNER CASES/BASE CASES
image

Recursive code

image

Memoized Recursive code
image

Memoized Recursive code (optimized)
image

Using Binary Search + Recursion

class Solution {
public:
    int dp[101][10005];
    int solve(int k,int n){
        if(n==0 or n==1)return n;
        if(k==1)return n;
        if(dp[k][n]!=-1){
            return dp[k][n];
        }
        int answer=INT_MAX;
        int start=1;
        int end=n;
        while(start<=end){
            int middle=(start+end)/2;
            int left=solve(k-1,middle-1);
            int right=solve(k,n-middle);
            int temp=1+max(left,right);
            if(left<right){
                start=middle+1;
            }
            else{
                end=middle-1;
            }
            answer=min(answer,temp);
        }
    return dp[k][n]=answer;
    }
    int superEggDrop(int k, int n) {
        memset(dp,-1,sizeof(dp));
        return solve(k,n);
    }
};

Do upvote if you like
Open to suggestions

Comments (1)