# Egg dropping problem using Dynamic Programming (DP)

In this article, we are going to implement a C++ program to solve the **Egg dropping problem using dynamic programming (DP)**.

Submitted by Ritik Aggarwal, on December 13, 2018

**Problem statement:** You are given **N** floor and **K** eggs. **You have to minimize the number of times you have to drop the eggs to find the critical floor where critical floor means the floor beyond which eggs start to break**. Assumptions of the problem:

- If egg breaks at
**i**floor then it also breaks at all greater floors.^{th} - If egg does not break at
**i**floor then it does not break at all lower floors.^{th} - Unbroken egg can be used again.

**Note:** You have to find minimum trials required to find the critical floor not the critical floor.

**Constraints:**

1 <= N <= 1000 1 <= K <= 100

**Example 1:**

Input: 4 2 Output: Number of trials when number of eggs is 2 and number of floors is 4: 3

**Example 2:**

Input: 36 2 Output: Number of trials when number of eggs is 2 and number of floors is 36: 8

**Explanation of the problem:**

**For the Input 1,**

**Case 1. Drop at first floor:**

**Egg does not break:**

If egg does not break then we have three floors left and two eggs. We can either choose**2**or^{nd}**3**floor and proceed similarly but we can easily see we have to do atleast 3 trials.^{rd}**Egg breaks:**

If egg breaks then we found the critical floor in only 1 trial.

In case 1, the worst possibility is that egg does not break so trials will be 3 for case 1.

**Case 2. Drop at second floor:**

**Egg breaks:**

We are left with one egg and we have to check only 1 floor so number of trials 2.**Egg does not break:**

We still have two eggs and two floors to check we have to check one by one on these floors so trials needed are 3.

So for case 2 together the worst possibility is 3.

In the end we have to find the minimum of case 1, case 2, case 3, case 4.

**Note:** Dropping from **3 ^{rd}** and

**4**floor is same as dropping from

^{th}**2**and

^{nd}**1**floor respectively only difference is that subcases

^{st}**A**and

**B**just gets swapped.

## Algorithm

- Create a 2D dp matrix where
**j**cell of ith row represents the minimum number of trials needed to check^{th}**i**floors using**j**eggs. - If there are 0 eggs then there are 0 trials so initializing all cell corresponding to this situation.
- If there are 1 egg then we have to drop egg at every floor so the number of trials is number of floors.
- If there are 0 floors so there are 0 trials and if there is one floor there is only one trial.
- Start filling the dp matrix from
**egg = 2 && floors = 2**. - We have to choose a floor
**x**between the 1 – floor and then find cases when egg breaks at**x**floor and egg do not break at^{th}**x**floors (^{th}**A**and**B**subparts of cases). - We have to take the maximum of these A and B subparts as we are taking worst case possible. Also, we will also add one to it as one trial is also needed to check
**x**floor.^{th} - Taking the minimum of answers of all such
**x's**and storing at my particular number of floors and number of eggs.

**The time complexity of the above code is O(N * K * K).**

## C++ program for Egg dropping problem using Dynamic Programming (DP)

#include <iostream> #include <limits.h> using namespace std; int eggDrop(int floors, int eggs){ int dp[floors + 1][eggs + 1] = {0}; // intializing with some cases // case 1. when there are 0 floors for(int egg = 0;egg<=eggs;egg++){ dp[0][egg] = 0; } // case 2. when there are only 1 floor so there // are only 1 way only check the first floor for(int egg = 0;egg<=eggs;egg++){ dp[1][egg] = 1; } // case 3. when there are 0 eggs for(int floor = 0;floor <=floors;floor++){ dp[floor][0] = 0; } // case 4. when there are 1 egg then we have to // check every floor so our answer would be number of // floors for(int floor = 0;floor <= floors;floor++){ dp[floor][1] = floor; } // we will start filling dp matrix from // floor = 2 && egg = 2 for(int egg = 2;egg<=eggs;egg++){ for(int floor = 2;floor<=floors;floor++){ // choosing an ith floor between 1 - floor int mini = INT_MAX; for(int i = 1;i<=floor;i++){ // dp[i - 1][egg-1] means to find the answer when // the egg is broken at ith floor // dp[floor - i][egg] means to find the answer // when the egg is not broken at ith floor int ans = max(dp[i-1][egg-1], dp[floor - i][egg]); // by trying to check the floor i have used one trial ans++; // taking the minimum of all possible floor // possible between 1 - floor mini = min(mini, ans); } // storing the answer dp[floor][egg] = mini; } } return dp[floors][eggs]; } // driver program int main() { int floors, eggs; cin >> floors >> eggs; cout<<"number of trials when number of eggs is " << eggs; cout<<" and number of floors is " << floors; cout<<": " << eggDrop(floors,eggs); return 0; }

**Output**

4 2 number of trials when number of eggs is 2 and number of floors is 4: 3

Related Tutorials

- Introduction to Algorithms
- Introduction to Greedy Strategy in Algorithms
- Stability in sorting
- External Merge Sorting Algorithm
- Radix Sort and its Algorithm
- Bucket Sort Algorithm
- Bubble sort Algorithm, Flow Chart and C++ Code
- Insertion sort Algorithm, flowchart and C, C++ Code
- Merge Sort | One of the best sorting algorithms used for large inputs
- Binary Search in C, C++
- Randomized Binary Search
- Meta Binary Search | One-sided Binary Search
- Difference between Linear Search and Binary Search
- Binary Search in String
- Variants of Binary Search
- Sieve of Eratosthenes to find prime numbers
- Optimal Merge Pattern (Algorithm and Example)
- Given an array of n numbers, Check whether there is any duplicate or not
- Finding the missing number
- Find the number occurring an odd number of times
- Find the pair whose sum is closest to zero in minimum time complexity
- Find three elements in an array such that their sum is equal to given element K
- Bitonic Search Algorithm
- Check whether a number is Fibonacci or not
- Segregate even and odd numbers in minimum time complexity
- Find trailing zeros in factorial of a number
- Find Nearest Greatest Neighbours of each element in an array
- Interpolation search algorithm
- Floor and ceil of an element in an array using C++
- Two Elements whose sum is closest to zero
- Find a pair with a given difference
- Count number of occurrences (or frequency) in a sorted array
- Find a Fixed Point (Value equal to index) in a given array
- Find the maximum element in an array which is first increasing and then decreasing
- Dynamic Programming (Components, Applications and Elements)
- Algorithm for fractional knapsack problem
- Algorithm and procedure to solve a longest common subsequence problem
- Find the Nth Fibonacci number | C++
- Longest Common Subsequence using Dynamic programming (DP)
- Longest Increasing Subsequence using Dynamic programming (DP)
- Find the maximum sub-array sum using KADANE'S ALGORITHM
- Non-intersecting chords using Dynamic Programming (DP)
- Edit Distance using Dynamic Programming (DP)
- Finding Ugly Number using Dynamic Programming (DP)
- Wild card matching problem using Dynamic programming (DP)
- Compute sum of digits in all numbers from 1 to N for a given N
- Minimum jumps required using Dynamic programming (DP)
- Graph coloring problem's solution using backtracking algorithm
- Breadth First Search (BFS) and Depth First Search (DFS) Algorithms
- Travelling Salesman Problem
- Kruskal's (P) and Prim's (K) Algorithms
- Multistage graph problem with forward approach and backward approach algorithms
- Floyd Warshall algorithm with its Pseudo Code

- Backtracking (Types and Algorithms)
- 4 Queen's problem and solution using backtracking algorithm
- N Queen's problem and solution using backtracking algorithm
- Find the GCD (Greatest Common Divisor) of two numbers using EUCLID'S ALGORITHM
- Compute the value of A raise to the power B using Fast Exponentiation
- Implement First Come First Served (FCFS) CPU Scheduling Algorithm using C program
- Implementations of FCFS scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Non-Preemptive CPU scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Preemptive CPU scheduling algorithm using C++
- Implementation of Priority scheduling (Pre-emptive) algorithm using C++
- Implementation of Priority scheduling (Non Pre-emptive) algorithm using C++
- Implementation of Round Robin CPU Scheduling algorithm using C++
- Analysis of LRU page replacement algorithm and Belady's anomaly
- Branch and Bound
- Find the roots of a complex polynomial equation using Regula Falsi Method in C
- Sieve of Eratosthenes to find prime numbers
- Implementations of FCFS scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Non-Preemptive CPU scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Preemptive CPU scheduling algorithm using C++
- Implementation of Priority scheduling (Pre-emptive) algorithm using C++
- Divide and Conquer Paradigm (What it is, Its Applications, Pros and Cons)
- Implementation of Priority scheduling (Non Pre-emptive) algorithm using C++
- Implementation of Round Robin CPU Scheduling algorithm using C++
- Jump Search Implementation using C++
- Optimal Merge Pattern (Algorithm and Example)
- Introduction to Greedy Strategy in Algorithms
- Strassen's Matrix Multiplication in algorithms
- Huffman Coding (Algorithm, Example and Time complexity)
- Backtracking (Types and Algorithms)
- 4 Queen's problem and solution using backtracking algorithm
- N Queen's problem and solution using backtracking algorithm
- Graph coloring problem's solution using backtracking algorithm
- Tournament Tree and their properties
- Deterministic and Non Deterministic Algorithms
- Lower Bound Theory
- Non Recursive Tree Traversal Algorithm
- Line Drawing Algorithm
- Breadth First Search (BFS) and Depth First Search (DFS) Algorithms
- P and NP problems and solutions | Algorithms
- Travelling Salesman Problem
- 2 – 3 Trees Algorithm
- Kruskal's (P) and Prim's (K) Algorithms
- Algorithm for fractional knapsack problem
- Algorithm and procedure to solve a longest common subsequence problem
- Midpoint Circle Algorithm
- Multistage graph problem with forward approach and backward approach algorithms
- Floyd Warshall algorithm with its Pseudo Code
- Reliability design problem
- Removing consecutive duplicates from a string
- Fast Exponentiation using Bitmasking

Comments and Discussions!