Egg Dropping Puzzle | DP-11
Last Updated :
01 Jul, 2024
The following is a description of the instance of this famous puzzle involving N = 2 eggs and a building with K = 36 floors.
Suppose that we wish to know which stories in a 36-story building are safe to drop eggs from, and which will cause the eggs to break on landing. We make a few assumptions:
- An egg that survives a fall can be used again.
- A broken egg must be discarded.
- The effect of a fall is the same for all eggs.
- If an egg breaks when dropped, then it would break if dropped from a higher floor.
- If an egg survives a fall then it would survive a shorter fall.
- It is not ruled out that the first-floor windows break eggs, nor is it ruled out that the 36th-floor does not cause an egg to break.
If only one egg is available and we wish to be sure of obtaining the right result, the experiment can be carried out in only one way. Drop the egg from the first-floor window; if it survives, drop it from the second-floor window. Continue upward until it breaks. In the worst case, this method may require 36 droppings. Suppose 2 eggs are available. What is the least number of egg droppings that are guaranteed to work in all cases?
The problem is not actually to find the critical floor, but merely to decide floors from which eggs should be dropped so that the total number of trials is minimized.
Note: In this post, we will discuss a solution to a general problem with ‘N’ eggs and ‘K’ floors
Egg Dropping Puzzle using Recursion:
To solve the problem follow the below idea:
The solution is to try dropping an egg from every floor(from 1 to K) and recursively calculate the minimum number of droppings needed in the worst case. The floor which gives the minimum value in the worst case is going to be part of the solution.
In the following solutions, we return the minimum number of trials in the worst case; these solutions can be easily modified to print the floor numbers of every trial also.
What is worst case scenario?
Worst case scenario gives the user the surety of the threshold floor. For example- If we have ‘1’ egg and ‘K’ floors, we will start dropping the egg from the first floor till the egg breaks suppose on the ‘Kth’ floor so the number of tries to give us surety is ‘K’.
1. Optimal Substructure:
When we drop an egg from floor x, there can be two cases (1) The egg breaks (2) The egg doesn’t break.
- If the egg breaks after dropping from ‘xth’ floor, then we only need to check for floors lower than ‘x’ with remaining eggs as some floors should exist lower than ‘x’ in which the egg would not break, so the problem reduces to x-1 floors and n-1 eggs.
- If the egg doesn’t break after dropping from the ‘xth’ floor, then we only need to check for floors higher than ‘x’; so the problem reduces to ‘k-x’ floors and n eggs.
Since we need to minimize the number of trials in the worst case, we take a maximum of two cases. We consider the max of the above two cases for every floor and choose the floor which yields the minimum number of trials.
Below is the illustration of the above approach:
K ==> Number of floors
N ==> Number of Eggs
eggDrop(N, K) ==> Minimum number of trials needed to find the critical
floor in worst case.
eggDrop(N, K) = 1 + min{max(eggDrop(N – 1, x – 1), eggDrop(N, K – x)), where x is in {1, 2, …, K}}
Concept of worst case:
Let there be ‘2’ eggs and ‘2’ floors then-:
If we try throwing from ‘1st’ floor:
Number of tries in worst case= 1+max(0, 1)
0=>If the egg breaks from first floor then it is threshold floor (best case possibility).
1=>If the egg does not break from first floor we will now have ‘2’ eggs and 1 floor to test which will give answer as
‘1’.(worst case possibility)
We take the worst case possibility in account, so 1+max(0, 1)=2
If we try throwing from ‘2nd’ floor:
Number of tries in worst case= 1+max(1, 0)
1=>If the egg breaks from second floor then we will have 1 egg and 1 floor to find threshold floor.(Worst Case)
0=>If egg does not break from second floor then it is threshold floor.(Best Case)
We take worst case possibility for surety, so 1+max(1, 0)=2.
The final answer is min(1st, 2nd, 3rd….., kth floor)
So answer here is ‘2’.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// A utility function to get
// maximum of two integers
int max(int a, int b) { return (a > b) ? a : b; }
// 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;
}
// Driver code
int main()
{
int n = 2, k = 10;
cout << "Minimum number of trials "
"in worst case with "
<< n << " eggs and " << k << " floors is "
<< eggDrop(n, k) << endl;
return 0;
}
// This code is contributed
// by Akanksha Rai
C
// C program for the above approach
#include <limits.h>
#include <stdio.h>
// A utility function to get
// maximum of two integers
int max(int a, int b) { return (a > b) ? a : b; }
/* 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;
}
/* Driver program to test to printDups*/
int main()
{
int n = 2, k = 10;
printf("Minimum number of trials in "
"worst case with %d eggs and "
"%d floors is %d \n",
n, k, eggDrop(n, k));
return 0;
}
Java
// Java program for the above approach
public class GFG {
/* Function to get minimum number of
trials needed in worst case with n
eggs and k floors */
static 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 = Integer.MAX_VALUE;
int 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 = Math.max(eggDrop(n - 1, x - 1),
eggDrop(n, k - x));
if (res < min)
min = res;
}
return min + 1;
}
// Driver code
public static void main(String args[])
{
int n = 2, k = 10;
System.out.print("Minimum number of "
+ "trials in worst case with " + n
+ " eggs and " + k + " floors is "
+ eggDrop(n, k));
}
// This code is contributed by Ryuga.
}
Python 3
import sys
# Function to get minimum number of trials
# needed in worst case with n eggs and k floors
def eggDrop(n, k):
# If there are no floors, then no trials
# needed. OR if there is one floor, one
# trial needed.
if (k == 1 or k == 0):
return k
# We need k trials for one egg
# and k floors
if (n == 1):
return k
min = sys.maxsize
# Consider all droppings from 1st
# floor to kth floor and return
# the minimum of these values plus 1.
for x in range(1, k + 1):
res = max(eggDrop(n - 1, x - 1),
eggDrop(n, k - x))
if (res < min):
min = res
return min + 1
# Driver Code
if __name__ == "__main__":
n = 2
k = 10
print("Minimum number of trials in worst case with",
n, "eggs and", k, "floors is", eggDrop(n, k))
# This code is contributed by ita_c
C#
using System;
class GFG {
/* Function to get minimum number of
trials needed in worst case with n
eggs and k floors */
static 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.MaxValue;
int 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 = Math.Max(eggDrop(n - 1, x - 1),
eggDrop(n, k - x));
if (res < min)
min = res;
}
return min + 1;
}
// Driver code
static void Main()
{
int n = 2, k = 10;
Console.Write("Minimum number of "
+ "trials in worst case with " + n
+ " eggs and " + k + " floors is "
+ eggDrop(n, k));
}
}
// This code is contributed by Sam007.
JavaScript
<script>
/* Function to get minimum number of
trials needed in worst case with n
eggs and k floors */
function eggDrop(n,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;
let min = Number.MAX_VALUE;
let 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 = Math.max(eggDrop(n - 1, x - 1),
eggDrop(n, k - x));
if (res < min)
min = res;
}
return min + 1;
}
// Driver code
let n = 2, k = 10;
document.write("Minimum number of "
+ "trials in worst case with "
+ n + " eggs and " + k
+ " floors is " + eggDrop(n, k));
// This code is contributed by avanitrachhadiya2155
</script>
OutputMinimum number of trials in worst case with 2 eggs and 10 floors is 4
Note: The above function computes the same subproblems again and again. See the following partial recursion tree, E(2, 2) is being evaluated twice. There will be many repeated subproblems when you draw the complete recursion tree even for small values of N and K.
E(2, 4)
|
-------------------------------------
| | | |
| | | |
x=1/ x=2/ x=3/ x=4/
/ / .... ....
/ /
E(1, 0) E(2, 3) E(1, 1) E(2, 2)
/ /... /
x=1/ .....
/
E(1, 0) E(2, 2)
/
......
Partial recursion tree for 2 eggs and 4 floors.
Time Complexity: As there is a case of overlapping sub-problems the time complexity is exponential.
Auxiliary Space: O(1). As there was no use of any data structure for storing values.
To solve the problem follow the below idea:
Since the same subproblems are called again, this problem has the Overlapping Subproblems property. So Egg Dropping Puzzle has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of the same subproblems can be avoided by constructing a temporary array eggFloor[][] in a bottom-up manner.
In this approach, we work on the same idea as described above neglecting the case of calculating the answers to sub-problems again and again. The approach will be to make a table that will store the results of sub-problems so that to solve a sub-problem, would only require a look-up from the table which will take constant time, which earlier took exponential time.
Formally for filling DP[i][j] state where ‘i’ is the number of eggs and ‘j’ is the number of floors:
We have to traverse for each floor ‘x’ from ‘1’ to ‘j’ and find a minimum of:
(1 + max( DP[i-1][j-1], DP[i][j-x] )).
Below is the illustration of the above approach:
i => Number of eggs
j => Number of floors
Look up find maximum
Lets fill the table for the following case:
Floors = ‘4’
Eggs = ‘2’
1 2 3 4
1 2 3 4 => 1
1 2 2 3 => 2
For ‘egg-1’ each case is the base case so the
number of attempts is equal to floor number.
For ‘egg-2’ it will take ‘1’ attempt for 1st
floor which is base case.
For floor-2 =>
Taking 1st floor 1 + max(0, DP[1][1])
Taking 2nd floor 1 + max(DP[1][1], 0)
DP[2][2] = min(1 + max(0, DP[1][1]), 1 + max(DP[1][1], 0))
For floor-3 =>
Taking 1st floor 1 + max(0, DP[2][2])
Taking 2nd floor 1 + max(DP[1][1], DP[2][1])
Taking 3rd floor 1 + max(0, DP[2][2])
DP[2][3]= min(‘all three floors’) = 2
For floor-4 =>
Taking 1st floor 1 + max(0, DP[2][3])
Taking 2nd floor 1 + max(DP[1][1], DP[2][2])
Taking 3rd floor 1 + max(DP[1][2], DP[2][1])
Taking 4th floor 1 + max(0, DP[2][3])
DP[2][4]= min(‘all four floors’) = 3
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// A utility function to get
// maximum of two integers
int max(int a, int b) { return (a > b) ? a : b; }
/* Function to get minimum
number of trials needed in worst
case with n eggs and k floors */
int eggDrop(int n, int k)
{
/* A 2D table where entry
eggFloor[i][j] will represent
minimum number of trials needed for
i eggs and j floors. */
int eggFloor[n + 1][k + 1];
int res;
int i, j, x;
// We need one trial for one floor and 0
// trials for 0 floors
for (i = 1; i <= n; i++) {
eggFloor[i][1] = 1;
eggFloor[i][0] = 0;
}
// We always need j trials for one egg
// and j floors.
for (j = 1; j <= k; j++)
eggFloor[1][j] = j;
// Fill rest of the entries in table using
// optimal substructure property
for (i = 2; i <= n; i++) {
for (j = 2; j <= k; j++) {
eggFloor[i][j] = INT_MAX;
for (x = 1; x <= j; x++) {
res = 1
+ max(eggFloor[i - 1][x - 1],
eggFloor[i][j - x]);
if (res < eggFloor[i][j])
eggFloor[i][j] = res;
}
}
}
// eggFloor[n][k] holds the result
return eggFloor[n][k];
}
// Driver code
int main()
{
int n = 2, k = 36;
cout << "\nMinimum number of trials "
"in worst case with "
<< n << " eggs and " << k << " floors is "
<< eggDrop(n, k);
return 0;
}
// this code is contributed by shivanisinghss2110
C
// C program for the above approach
#include <limits.h>
#include <stdio.h>
// A utility function to get
// maximum of two integers
int max(int a, int b) { return (a > b) ? a : b; }
/* Function to get minimum
number of trials needed in worst
case with n eggs and k floors */
int eggDrop(int n, int k)
{
/* A 2D table where entry
eggFloor[i][j] will represent
minimum number of trials needed for
i eggs and j floors. */
int eggFloor[n + 1][k + 1];
int res;
int i, j, x;
// We need one trial for one floor and 0
// trials for 0 floors
for (i = 1; i <= n; i++) {
eggFloor[i][1] = 1;
eggFloor[i][0] = 0;
}
// We always need j trials for one egg
// and j floors.
for (j = 1; j <= k; j++)
eggFloor[1][j] = j;
// Fill rest of the entries in table using
// optimal substructure property
for (i = 2; i <= n; i++) {
for (j = 2; j <= k; j++) {
eggFloor[i][j] = INT_MAX;
for (x = 1; x <= j; x++) {
res = 1
+ max(eggFloor[i - 1][x - 1],
eggFloor[i][j - x]);
if (res < eggFloor[i][j])
eggFloor[i][j] = res;
}
}
}
// eggFloor[n][k] holds the result
return eggFloor[n][k];
}
// Driver code
int main()
{
int n = 2, k = 36;
printf("\nMinimum number of trials "
"in worst case with %d eggs and "
"%d floors is %d \n",
n, k, eggDrop(n, k));
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class EggDrop {
// A utility function to get
// maximum of two integers
static int max(int a, int b) { return (a > b) ? a : b; }
/* Function to get minimum number
of trials needed in worst
case with n eggs and k floors */
static int eggDrop(int n, int k)
{
/* A 2D table where entry eggFloor[i][j]
will represent minimum number of trials
needed for i eggs and j floors. */
int eggFloor[][] = new int[n + 1][k + 1];
int res;
int i, j, x;
// We need one trial for one floor and
// 0 trials for 0 floors
for (i = 1; i <= n; i++) {
eggFloor[i][1] = 1;
eggFloor[i][0] = 0;
}
// We always need j trials for one egg
// and j floors.
for (j = 1; j <= k; j++)
eggFloor[1][j] = j;
// Fill rest of the entries in table using
// optimal substructure property
for (i = 2; i <= n; i++) {
for (j = 2; j <= k; j++) {
eggFloor[i][j] = Integer.MAX_VALUE;
for (x = 1; x <= j; x++) {
res = 1
+ max(eggFloor[i - 1][x - 1],
eggFloor[i][j - x]);
if (res < eggFloor[i][j])
eggFloor[i][j] = res;
}
}
}
// eggFloor[n][k] holds the result
return eggFloor[n][k];
}
/* Driver code */
public static void main(String args[])
{
int n = 2, k = 36;
System.out.println(
"Minimum number of trials in worst"
+ " case with " + n + " eggs and " + k
+ " floors is " + eggDrop(n, k));
}
}
/*This code is contributed by Rajat Mishra*/
Python
# Python3 program for the above approach
INT_MAX = 32767
# Function to get minimum number of trials needed in worst
# case with n eggs and k floors
def eggDrop(n, k):
# A 2D table where entry eggFloor[i][j] will represent minimum
# number of trials needed for i eggs and j floors.
eggFloor = [[0 for x in range(k + 1)] for x in range(n + 1)]
# We need one trial for one floor and0 trials for 0 floors
for i in range(1, n + 1):
eggFloor[i][1] = 1
eggFloor[i][0] = 0
# We always need j trials for one egg and j floors.
for j in range(1, k + 1):
eggFloor[1][j] = j
# Fill rest of the entries in table using optimal substructure
# property
for i in range(2, n + 1):
for j in range(2, k + 1):
eggFloor[i][j] = INT_MAX
for x in range(1, j + 1):
res = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x])
if res < eggFloor[i][j]:
eggFloor[i][j] = res
# eggFloor[n][k] holds the result
return eggFloor[n][k]
# Driver code
if __name__ == "__main__":
n = 2
k = 36
print("Minimum number of trials in worst case with " + str(n) + " eggs and "
+ str(k) + " floors is " + str(eggDrop(n, k)))
# This code is contributed by Bhavya Jain
C#
// C# program for the above approach
using System;
class GFG {
// A utility function to get maximum of
// two integers
static int max(int a, int b) { return (a > b) ? a : b; }
/* Function to get minimum number of
trials needed in worst case with n
eggs and k floors */
static int eggDrop(int n, int k)
{
/* A 2D table where entry eggFloor[i][j]
will represent minimum number of trials
needed for i eggs and j floors. */
int[, ] eggFloor = new int[n + 1, k + 1];
int res;
int i, j, x;
// We need one trial for one floor and0
// trials for 0 floors
for (i = 1; i <= n; i++) {
eggFloor[i, 1] = 1;
eggFloor[i, 0] = 0;
}
// We always need j trials for one egg
// and j floors.
for (j = 1; j <= k; j++)
eggFloor[1, j] = j;
// Fill rest of the entries in table
// using optimal substructure property
for (i = 2; i <= n; i++) {
for (j = 2; j <= k; j++) {
eggFloor[i, j] = int.MaxValue;
for (x = 1; x <= j; x++) {
res = 1
+ max(eggFloor[i - 1, x - 1],
eggFloor[i, j - x]);
if (res < eggFloor[i, j])
eggFloor[i, j] = res;
}
}
}
// eggFloor[n][k] holds the result
return eggFloor[n, k];
}
// Driver code
public static void Main()
{
int n = 2, k = 36;
Console.WriteLine("Minimum number of trials "
+ "in worst case with " + n
+ " eggs and " + k + "floors is "
+ eggDrop(n, k));
}
}
// This code is contributed by Sam007.
JavaScript
<script>
// A Dynamic Programming based JavaScript
// Program for the Egg Dropping Puzzle
// A utility function to get
// maximum of two integers
function max(a,b)
{
return (a > b) ? a : b;
}
/* Function to get minimum number
of trials needed in worst
case with n eggs and k floors */
function eggDrop(n,k)
{
/* A 2D table where entry eggFloor[i][j]
will represent minimum number of trials
needed for i eggs and j floors. */
let eggFloor = new Array(n + 1);
for(let i=0;i<(n+1);i++)
{
eggFloor[i]=new Array(k+1);
}
let res;
let i, j, x;
// We need one trial for one floor and
// 0 trials for 0 floors
for (i = 1; i <= n; i++) {
eggFloor[i][1] = 1;
eggFloor[i][0] = 0;
}
// We always need j trials for one egg
// and j floors.
for (j = 1; j <= k; j++)
eggFloor[1][j] = j;
// Fill rest of the entries in table using
// optimal substructure property
for (i = 2; i <= n; i++) {
for (j = 2; j <= k; j++) {
eggFloor[i][j] = Number.MAX_VALUE;
for (x = 1; x <= j; x++) {
res = 1 + max(
eggFloor[i - 1][x - 1],
eggFloor[i][j - x]);
if (res < eggFloor[i][j])
eggFloor[i][j] = res;
}
}
}
// eggFloor[n][k] holds the result
return eggFloor[n][k];
}
/* Driver program to test to printDups*/
let n = 2, k = 36;
document.write("Minimum number of trials in worst"
+ " case with "
+ n + " eggs and "
+ k + " floors is " + eggDrop(n, k));
// This code is contributed by ab2127
</script>
PHP
<?php
// A Dynamic Programming based PHP
// Program for the Egg Dropping Puzzle
/* Function to get minimum number
of trials needed in worst
case with n eggs and k floors */
function eggDrop($n, $k)
{
/* A 2D table where entry eggFloor[i][j]
will represent minimum number of
trials needed for i eggs and j floors. */
$eggFloor = array(array());;
// We need one trial for one
// floor and0 trials for 0 floors
for ($i = 1; $i <=$n;$i++)
{
$eggFloor[$i][1] = 1;
$eggFloor[$i][0] = 0;
}
// We always need j trials
// for one egg and j floors.
for ($j = 1; $j <= $k; $j++)
$eggFloor[1][$j] = $j;
// Fill rest of the entries in
// table using optimal substructure
// property
for ($i = 2; $i <= $n; $i++)
{
for ($j = 2; $j <= $k; $j++)
{
$eggFloor[$i][$j] = 999999;
for ($x = 1; $x <= $j; $x++)
{
$res = 1 + max($eggFloor[$i - 1][$x - 1],
$eggFloor[$i][$j - $x]);
if ($res < $eggFloor[$i][$j])
$eggFloor[$i][$j] = $res;
}
}
}
// eggFloor[n][k] holds the result
return $eggFloor[$n][$k];
}
// Driver Code
$n = 2;
$k = 36;
echo "Minimum number of trials in worst case with " .$n. " eggs and "
.$k. " floors is " .eggDrop($n, $k) ;
// This code is contributed by Sam007
?>
OutputMinimum number of trials in worst case with 2 eggs and 36 floors is 8
Time Complexity: O(N * K2). As we use a nested for loop ‘k^2’ times for each egg
Auxiliary Space: O(N * K). A 2-D array of size ‘n*k’ is used for storing elements.
Egg Dropping Puzzle using Memoization:
To solve the problem follow the below idea:
We can use a 2D dp table in the first recursive approach to store the results of overlapping subproblems which will help to reduce the time complexity from exponential to quadratic
dp table state –> dp[i][j], where where ‘i’ is the number of eggs and ‘j’ is the number of floors:
Follow the below steps to solve the problem:
- Declare a 2-D array memo of size N+1 * K+1 and call the function solveEggDrop(N, K)
- If memo[N][K] is already computed then return memo[n][k]
- If K == 1 or K == 0 then return K (Base Case)
- If N == 1 return K (Base case)
- Create an integer min equal to the integer Maximum and an integer res
- Run a for loop from x equal to 1 till x is less than or equal to K
- Set res equal to maximum of solveEggDrop(N-1, x-1) or solveEggDrop(N, k-x)
- If res is less than integer min then set min equal to res
- Set memo[N][K] equal to min + 1
- Return min + 1
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
vector<vector<int> > memo(MAX, vector<int>(MAX, -1));
int solveEggDrop(int n, int k)
{
if (memo[n][k] != -1) {
return memo[n][k];
}
if (k == 1 || k == 0)
return k;
if (n == 1)
return k;
int min = INT_MAX, x, res;
for (x = 1; x <= k; x++) {
res = max(solveEggDrop(n - 1, x - 1),
solveEggDrop(n, k - x));
if (res < min)
min = res;
}
memo[n][k] = min + 1;
return min + 1;
}
// Driver code
int main()
{
int n = 2, k = 36;
cout << "Minimum number of trials "
"in worst case with "
<< n << " eggs and " << k << " floors is ";
cout << solveEggDrop(n, k);
return 0;
}
// contributed by Shivam Agrawal(shivamagrawal3)
C
// C program for the above approach
#include <limits.h>
#include <stdio.h>
#include <string.h>
#define MAX 1000
int memo[MAX][MAX];
int solveEggDrop(int n, int k)
{
if (memo[n][k] != -1) {
return memo[n][k];
}
if (k == 1 || k == 0)
return k;
if (n == 1)
return k;
int min = INT_MAX, x, res;
for (x = 1; x <= k; x++) {
int a = solveEggDrop(n - 1, x - 1);
int b = solveEggDrop(n, k - x);
res = a > b ? a : b;
if (res < min)
min = res;
}
memo[n][k] = min + 1;
return min + 1;
}
// Driver code
int main()
{
memset(memo, -1, MAX * MAX * sizeof(int));
int n = 2, k = 36;
printf("Minimum number of trials in worst case with %d eggs and %d floors is ",n,k);
printf("%d", solveEggDrop(n, k));
return 0;
}
// This code is contributed by repakaeswaripriya.
Java
// Java program for the above approach
import java.util.Arrays;
class GFG {
static final int MAX = 1000;
static int[][] memo = new int[MAX][MAX];
static int solveEggDrop(int n, int k)
{
if (memo[n][k] != -1) {
return memo[n][k];
}
if (k == 1 || k == 0)
return k;
if (n == 1)
return k;
int min = Integer.MAX_VALUE, x, res;
for (x = 1; x <= k; x++) {
res = Math.max(solveEggDrop(n - 1, x - 1),
solveEggDrop(n, k - x));
if (res < min)
min = res;
}
memo[n][k] = min + 1;
return min + 1;
}
// Driver code
public static void main(String[] args)
{
for (int i = 0; i < memo.length; i++)
Arrays.fill(memo[i], -1);
int n = 2, k = 36;
System.out.print("Minimum number of trials in worst case with "
+ n + " eggs and " + k + " floors is ");
System.out.print(solveEggDrop(n, k));
}
}
// This code IS contributed by umadevi9616
Python
# Python3 program for the above approach
import sys
MAX = 1000
memo = [[-1 for i in range(MAX)] for j in range(MAX)]
def solveEggDrop(n, k):
if (memo[n][k] != -1):
return memo[n][k]
if (k == 1 or k == 0):
return k
if (n == 1):
return k
min = sys.maxsize
res = 0
for x in range(1, k+1):
res = max(solveEggDrop(n - 1, x - 1), solveEggDrop(n, k - x))
if (res < min):
min = res
memo[n][k] = min + 1
return min + 1
# Driver code
if __name__ == '__main__':
n = 2
k = 36
print("Minimum number of trials in worst case with " , n, " eggs and ", k, " floors is ", solveEggDrop(n, k))
# This code is contributed by gauravrajput1
C#
// C# program for the above approach
using System;
public class GFG {
static readonly int MAX = 1000;
static int[, ] memo = new int[MAX, MAX];
static int solveEggDrop(int n, int k)
{
if (memo[n, k] != -1) {
return memo[n, k];
}
if (k == 1 || k == 0)
return k;
if (n == 1)
return k;
int min = int.MaxValue, x, res;
for (x = 1; x <= k; x++) {
res = Math.Max(solveEggDrop(n - 1, x - 1),
solveEggDrop(n, k - x));
if (res < min)
min = res;
}
memo[n, k] = min + 1;
return min + 1;
}
// Driver code
public static void Main(String[] args)
{
for (int i = 0; i < memo.GetLength(0); i++)
for (int j = 0; j < memo.GetLength(1); j++)
memo[i, j] = -1;
int n = 2, k = 36;
Console.Write("Minimum number of trials in worst case with "
+ n + " eggs and " + k + " floors is ");
Console.Write(solveEggDrop(n, k));
}
}
// This code is contributed by gauravrajput1
JavaScript
<script>
var MAX = 1000;
var memo = Array(MAX).fill().map(()=>Array(MAX).fill(-1));
function solveEggDrop(n , k)
{
if (memo[n][k] != -1) {
return memo[n][k];
}
if (k == 1 || k == 0)
return k;
if (n == 1)
return k;
var min = Number.MAX_VALUE, x, res;
for (x = 1; x <= k; x++) {
res = Math.max(solveEggDrop(n - 1, x - 1),
solveEggDrop(n, k - x));
if (res < min)
min = res;
}
memo[n][k] = min + 1;
return min + 1;
}
var n = 2, k = 36;
document.write(solveEggDrop(n, k));
// This code is contributed by gauravrajput1
</script>
OutputMinimum number of trials in worst case with 2 eggs and 36 floors is 8
Time Complexity: O(n*k*k) where n is number of eggs and k is number of floors.
Auxiliary Space: O(n*k) as 2D memoisation table has been used.
Approach: To solve the problem follow the below idea:
The approach with O(N * K2) has been discussed before, where dp[N][K] = 1 + max(dp[N – 1][i – 1], dp[N][K – i]) for i in 1…K. You checked all the possibilities in that approach.
Consider the problem in a different way:
dp[m][x] means that, given x eggs and m moves,
what is the maximum number of floors that can be checked
The DP equation is: dp[m][x] = 1 + dp[m – 1][x – 1] + dp[m – 1][x],
which means we take 1 move to a floor.
If egg breaks, then we can check dp[m – 1][x – 1] floors.
If egg doesn’t break, then we can check dp[m – 1][x] floors.
Follow the below steps to solve the problem:
- Declare a 2-D array of size K+1 * N+1 and an integer m equal to zero
- While dp[m][n] < k
- increase ‘m’ by 1 and run a for loop from x equal to one till x is less than or equal to n
- Set dp[m][x] equal to 1 + dp[m-1][x-1] + dp[m-1][x]
- Return m
Below is the implementation of the above approach:
C++
// C++ program to find minimum number of trials in worst
// case.
#include <bits/stdc++.h>
using namespace std;
int minTrials(int n, int k)
{
// Initialize 2D of size (k+1) * (n+1).
vector<vector<int> > dp(k + 1, vector<int>(n + 1, 0));
int m = 0; // Number of moves
while (dp[m][n] < k) {
m++;
for (int x = 1; x <= n; x++) {
dp[m][x] = 1 + dp[m - 1][x - 1] + dp[m - 1][x];
}
}
return m;
}
/* Driver code*/
int main()
{
int n = 2, k = 36;
cout<<"Minimum number of trials "
"in worst case with "
<< n << " eggs and " << k << " floors is ";
cout << minTrials(2, 36);
return 0;
}
// This code is contributed by Arihant Jain (arihantjain01)
Java
// Java program to find minimum number of trials in worst
// case.
import java.util.*;
public class Main {
static int minTrials(int n, int k)
{
// Initialize 2D of size (k+1) * (n+1).
int dp[][] = new int[k + 1][n + 1];
int m = 0; // Number of moves
while (dp[m][n] < k) {
m++;
for (int x = 1; x <= n; x++) {
dp[m][x] = 1 + dp[m - 1][x - 1] + dp[m - 1][x];
}
}
return m;
}
/* Driver code*/
public static void main(String[] args)
{
int n = 2, k = 36;
System.out.println("Minimum number of trials "
+ "in worst case with " + n + " eggs and "
+ k + " floors is "+ minTrials(2, 36));
}
}
Python
def minTrials(n, k):
# Initialize 2D array of size (k+1) * (n+1).
dp = [[0 for x in range(n + 1)] for y in range(k + 1)]
m = 0 # Number of moves
while dp[m][n] < k:
m += 1
for x in range(1, n + 1):
dp[m][x] = 1 + dp[m - 1][x - 1] + dp[m - 1][x]
return m
# Driver code
n, k = 2, 36
print("Minimum number of trials in worst case with", n, "eggs and", k, "floors is", minTrials(n, k))
C#
using System;
class Program {
static int minTrials(int n, int k)
{
// Initialize 2D array of size (k+1) * (n+1).
int[, ] dp = new int[k + 1, n + 1];
int m = 0;
// Number of moves
while (dp[m, n] < k) {
m += 1;
for (int x = 1; x <= n; x++) {
dp[m, x]
= 1 + dp[m - 1, x - 1] + dp[m - 1, x];
}
}
return m;
}
static void Main(string[] args)
{
int n = 2, k = 36;
Console.WriteLine(
"Minimum number of trials in worst case with {0} eggs and {1} floors is {2}",
n, k, minTrials(n, k));
}
}
// This code is contributed by Amit Mangal.
JavaScript
function minTrials(n, k) {
// Initialize 2D array of size (k+1) * (n+1).
let dp = Array.from(Array(k + 1), () => Array(n + 1).fill(0));
let m = 0; // Number of moves
while (dp[m][n] < k) {
m += 1;
for (let x = 1; x <= n; x++) {
dp[m][x] = 1 + dp[m - 1][x - 1] + dp[m - 1][x];
}
}
return m;
}
// Driver code
let n = 2, k = 36;
console.log("Minimum number of trials in worst case with", n, "eggs and", k, "floors is", minTrials(n, k));
// This code is contributed by Amit Mangal.
OutputMinimum number of trials in worst case with 2 eggs and 36 floors is 8
Time Complexity: O(N * K)
Auxiliary Space: O(N * K)
Egg Dropping Puzzle using space-optimized DP:
The fourth approach can be optimized to 1-D DP as for calculating the current row of the DP table, we require only the previous row results and not beyond that.
Follow the below steps to solve the problem:
- Create an array dp of size N+1 and an integer m
- Run a for loop from m equal to zero till dp[n] < k
- Run a nested for loop from x equal to n till x is greater than zero
- Set dp[x] equal to 1 + dp[x-1]
- Return m
Below is the implementation of the above approach:
C++
// C++ program to find minimum number of trials in worst
// case.
#include <bits/stdc++.h>
using namespace std;
int minTrials(int n, int k)
{
// Initialize array of size (n+1) and m as moves.
int dp[n + 1] = { 0 }, m;
for (m = 0; dp[n] < k; m++) {
for (int x = n; x > 0; x--) {
dp[x] += 1 + dp[x - 1];
}
}
return m;
}
/* Driver code*/
int main()
{
int n = 2, k = 36;
cout<<"Minimum number of trials "
"in worst case with "
<< n << " eggs and " << k << " floors is ";
cout << minTrials(2, 36);
return 0;
}
// This code is contributed by Arihant Jain (arihantjain01)
Java
// Java program to find minimum number of trials in worst
// case.
import java.io.*;
class GFG {
static int minTrials(int n, int k)
{
// Initialize array of size (n+1) and m as moves.
int dp[] = new int[n + 1], m;
for (m = 0; dp[n] < k; m++) {
for (int x = n; x > 0; x--) {
dp[x] += 1 + dp[x - 1];
}
}
return m;
}
/* Driver code*/
public static void main(String[] args)
{
int n = 2, k = 36;
System.out.println("Minimum number of trials "
+ "in worst case with "
+ n + " eggs and " + k + " floors is " +
minTrials(2, 36));
}
}
// This code contributed by SRJ
Python
# Python implementation for the above approach.
def minTrials(n, k):
# Initialize array of size (n+1) and m as moves.
dp = [0 for i in range(n+1)]
m = 0
while dp[n] < k:
m += 1
for x in range(n, 0, -1):
dp[x] += 1 + dp[x - 1]
return m
# Driver code
n, k = 2, 36
print("Minimum number of trials in worst case with",
n, "eggs and", k, "floors is", minTrials(n, k))
# This code is contributed by Amit Mangal.
C#
// C# implementation for the above approach.
using System;
class Program {
static int minTrials(int n, int k)
{
// Initialize array of size (n+1) and m as moves.
int[] dp = new int[n + 1];
int m;
for (m = 0; dp[n] < k; m++) {
for (int x = n; x > 0; x--) {
dp[x] += 1 + dp[x - 1];
}
}
return m;
}
// Driver Code
static void Main(string[] args)
{
int n = 2, k = 36;
Console.WriteLine(
"Minimum number of trials in worst case with {0} eggs and {1} floors is {2}",
n, k, minTrials(n, k));
}
}
// This code is contributed by Amit Mangal.
JavaScript
// Javascript program to find minimum number of trials in worst case.
function minTrials(n, k)
{
// Initialize array of size (n+1) and m as moves.
let dp = new Array(n + 1);
dp.fill(0);
let m;
for (m = 0; dp[n] < k; m++) {
for (let x = n; x > 0; x--) {
dp[x] += 1 + dp[x - 1];
}
}
return m;
}
/* Driver code*/
let n = 2,
k = 36;
console.log(
"Minimum number of trials " +
"in worst case with " +
n + " eggs and " +
k + " floors is "
);
console.log(minTrials(2, 36));
// This code is contributed by satwiksuman.
OutputMinimum number of trials in worst case with 2 eggs and 36 floors is 8
Time Complexity: O(N * K)
Auxiliary Space: O(N)
Related Articles:
Eggs dropping puzzle (Binomial Coefficient and Binary Search Solution)
Egg Dropping Puzzle with 2 Eggs and K Floors
2 Eggs and 100 Floor Puzzle
References: http://archive.ite.journal.informs.org/Vol4No1/Sniedovich/index.php
Similar Reads
Dynamic Programming or DP
Dynamic Programming is an algorithmic technique with the following properties. It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
What is Memoization? A Complete Tutorial
In this tutorial, we will dive into memoization, a powerful optimization technique that can drastically improve the performance of certain algorithms. Memoization helps by storing the results of expensive function calls and reusing them when the same inputs occur again. This avoids redundant calcula
6 min read
Dynamic Programming (DP) Introduction
Dynamic Programming is a commonly used algorithmic technique used to optimize recursive solutions when same subproblems are called again. The core idea behind DP is to store solutions to subproblems so that each is solved only once. To solve DP problems, we first write a recursive solution in a way
15+ min read
Tabulation vs Memoization
Tabulation and memoization are two techniques used to implement dynamic programming. Both techniques are used when there are overlapping subproblems (the same subproblem is executed multiple times). Below is an overview of two approaches. Memoization:Top-down approachStores the results of function c
9 min read
Optimal Substructure Property in Dynamic Programming | DP-2
The following are the two main properties of a problem that suggest that the given problem can be solved using Dynamic programming: 1) Overlapping Subproblems 2) Optimal Substructure We have already discussed the Overlapping Subproblem property. Let us discuss the Optimal Substructure property here.
4 min read
Overlapping Subproblems Property in Dynamic Programming | DP-1
Dynamic Programming is an algorithmic paradigm that solves a given complex problem by breaking it into subproblems using recursion and storing the results of subproblems to avoid computing the same results again. Following are the two main properties of a problem that suggests that the given problem
10 min read
Steps to solve a Dynamic Programming Problem
Steps to solve a Dynamic programming problem:Identify if it is a Dynamic programming problem.Decide a state expression with the Least parameters.Formulate state and transition relationship.Apply tabulation or memorization.Step 1: How to classify a problem as a Dynamic Programming Problem? Typically,
14 min read
Advanced Topics
Count Ways To Assign Unique Cap To Every Person
Given n people and 100 types of caps labelled from 1 to 100, along with a 2D integer array caps where caps[i] represents the list of caps preferred by the i-th person, the task is to determine the number of ways the n people can wear different caps. Example: Input: caps = [[3, 4], [4, 5], [5]] Outpu
15+ min read
Digit DP | Introduction
Prerequisite : How to solve a Dynamic Programming Problem ?There are many types of problems that ask to count the number of integers 'x' between two integers say 'a' and 'b' such that x satisfies a specific property that can be related to its digits.So, if we say G(x) tells the number of such intege
14 min read
Sum over Subsets | Dynamic Programming
Prerequisite: Basic Dynamic Programming, Bitmasks Consider the following problem where we will use Sum over subset Dynamic Programming to solve it. Given an array of 2n integers, we need to calculate function F(x) = ?Ai such that x&i==i for all x. i.e, i is a bitwise subset of x. i will be a bit
10 min read
Easy problems in Dynamic programming
Coin Change - Count Ways to Make Sum
Given an integer array of coins[] of size n representing different types of denominations and an integer sum, the task is to count all combinations of coins to make a given value sum. Note: Assume that you have an infinite supply of each type of coin. Examples: Input: sum = 4, coins[] = [1, 2, 3]Out
15+ min read
Subset Sum Problem
Given an array arr[] of non-negative integers and a value sum, the task is to check if there is a subset of the given array whose sum is equal to the given sum. Examples: Input: arr[] = {3, 34, 4, 12, 5, 2}, sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input: arr[] = {3, 34,
15+ min read
Introduction and Dynamic Programming solution to compute nCr%p
Given three numbers n, r and p, compute value of nCr mod p. Example: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6.We strongly recommend that you click here and practice it, before moving on to the solution.METHOD 1: (Using Dynamic Programming) A Simple Solution is
15+ min read
Rod Cutting
Given a rod of length n inches and an array price[]. price[i] denotes the value of a piece of length i. The task is to determine the maximum value obtainable by cutting up the rod and selling the pieces. Note: price[] is 1-indexed array. Input: price[] = [1, 5, 8, 9, 10, 17, 17, 20]Output: 22Explana
15+ min read
Painting Fence Algorithm
Given a fence with n posts and k colors, the task is to find out the number of ways of painting the fence so that not more than two consecutive posts have the same color. Examples: Input: n = 2, k = 4Output: 16Explanation: We have 4 colors and 2 posts.Ways when both posts have same color: 4 Ways whe
15 min read
Longest Common Subsequence (LCS)
Given two strings, s1 and s2, the task is to find the length of the Longest Common Subsequence. If there is no common subsequence, return 0. A subsequence is a string generated from the original string by deleting 0 or more characters and without changing the relative order of the remaining characte
15+ min read
Longest Increasing Subsequence (LIS)
Given an array arr[] of size n, the task is to find the length of the Longest Increasing Subsequence (LIS) i.e., the longest possible subsequence in which the elements of the subsequence are sorted in increasing order. Examples: Input: arr[] = [3, 10, 2, 1, 20]Output: 3Explanation: The longest incre
15+ min read
Longest subsequence such that difference between adjacents is one
Given an array arr[] of size n, the task is to find the longest subsequence such that the absolute difference between adjacent elements is 1. Examples: Input: arr[] = [10, 9, 4, 5, 4, 8, 6]Output: 3Explanation: The three possible subsequences of length 3 are [10, 9, 8], [4, 5, 4], and [4, 5, 6], whe
15+ min read
Maximum size square sub-matrix with all 1s
Given a binary matrix mat of size n * m, the task is to find out the maximum length of a side of a square sub-matrix with all 1s. Example: Input: mat = [ [0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0] ] Output: 3Explanation: The maximum length of
15+ min read
Min Cost Path
Given a 2d matrix cost[][], the task is to calculate the minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a cost to traverse through that cell. The total cost of a path to reach (m, n) is the sum of all the costs on that path (including both source and destination).
15+ min read
Longest Common Substring (Space optimized DP solution)
Given two strings ‘s1‘ and ‘s2‘, find the length of the longest common substring. Example: Input: s1 = “GeeksforGeeks”, s2 = “GeeksQuiz” Output : 5 Explanation:The longest common substring is “Geeks” and is of length 5. Input: s1 = “abcdxyz”, s2 = “xyzabcd” Output : 4Explanation:The longest common s
7 min read
Count ways to reach the nth stair using step 1, 2 or 3
A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. The task is to implement a method to count how many possible ways the child can run up the stairs. Examples: Input: 4Output: 7Explanation: There are seven ways: {1, 1, 1, 1}, {1, 2, 1}, {2, 1, 1}
15+ min read
Grid Unique Paths - Count Paths in matrix
Given an matrix of size m x n, the task is to find the count of all unique possible paths from top left to the bottom right with the constraints that from each cell we can either move only to the right or down. Examples: Input: m = 2, n = 2Output: 2Explanation: There are two paths(0, 0) -> (0, 1)
15+ min read
Unique paths in a Grid with Obstacles
Given a grid[][] of size m * n, let us assume we are starting at (1, 1) and our goal is to reach (m, n). At any instance, if we are on (x, y), we can either go to (x, y + 1) or (x + 1, y). The task is to find the number of unique paths if some obstacles are added to the grid.Note: An obstacle and sp
15+ min read
Medium problems on Dynamic programming
0/1 Knapsack Problem
Given N items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. Note: The constraint
15+ min read
Printing Items in 0/1 Knapsack
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays, val[0..n-1] and wt[0..n-1] represent values and weights associated with n items respectively. Also given an integer W which repre
12 min read
Unbounded Knapsack (Repetition of items allowed)
Given a knapsack weight, say capacity and a set of n items with certain value vali and weight wti, The task is to fill the knapsack in such a way that we can get the maximum profit. This is different from the classical Knapsack problem, here we are allowed to use an unlimited number of instances of
15+ min read
Egg Dropping Puzzle | DP-11
The following is a description of the instance of this famous puzzle involving N = 2 eggs and a building with K = 36 floors.Suppose that we wish to know which stories in a 36-story building are safe to drop eggs from, and which will cause the eggs to break on landing. We make a few assumptions: An e
15+ min read
Word Break
Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words. See following examples for more details. This is a famous Google interview question, also being asked by many other companies now a days. Consider the f
15+ min read
Vertex Cover Problem (Dynamic Programming Solution for Tree)
A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either ‘u’ or ‘v’ is in vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph. The problem to find minimum size vertex cover of a graph is NP complet
15+ min read
Tile Stacking Problem
Given integers n (the height of the tower), m (the maximum size of tiles available), and k (the maximum number of times each tile size can be used), the task is to calculate the number of distinct stable towers of height n that can be built. Note: A stable tower consists of exactly n tiles, each sta
15+ min read
Box Stacking Problem
Given three arrays height[], width[], and length[] of size n, where height[i], width[i], and length[i] represent the dimensions of a box. The task is to create a stack of boxes that is as tall as possible, but we can only stack a box on top of another box if the dimensions of the 2-D base of the low
15+ min read
Partition a Set into Two Subsets of Equal Sum
Given an array arr[], the task is to check if it can be partitioned into two parts such that the sum of elements in both parts is the same. Examples: Input: arr[] = [1, 5, 11, 5]Output: True Explanation: The array can be partitioned as [1, 5, 5] and [11] Input: arr[] = [1, 5, 3]Output: False Explana
15+ min read
Travelling Salesman Problem using Dynamic Programming
Given a 2d matrix cost[][] of size n where cost[i][j] denotes the cost of moving from city i to city j. The task is to complete a tour from city 0 (0-based index) to all other cities such that we visit each city exactly once and then at the end come back to city 0 at minimum cost. Note the differenc
15 min read
Longest Palindromic Subsequence (LPS)
Given a string 'S', find the length of the Longest Palindromic Subsequence in it. The Longest Palindromic Subsequence (LPS) is the problem of finding a maximum-length subsequence of a given string that is also a Palindrome. Examples: Input: S = "GEEKSFORGEEKS"Output: 5Explanation: The longest palind
15+ min read
Longest Common Increasing Subsequence (LCS + LIS)
Given two arrays, a[] and b[], find the length of the longest common increasing subsequence(LCIS). LCIS refers to a subsequence that is present in both arrays and strictly increases.Prerequisites: LCS, LIS. Examples: Input: a[] = [3, 4, 9, 1], b[] = [5, 3, 8, 9, 10, 2, 1]Output: 2Explanation: The lo
15+ min read
Find all distinct subset (or subsequence) sums of an array
Given an array arr[] of size n, the task is to find a distinct sum that can be generated from the subsets of the given sets and return them in increasing order. It is given that the sum of array elements is small. Examples: Input: arr[] = [1, 2]Output: [0, 1, 2, 3]Explanation: Four distinct sums can
15+ min read
Weighted Job Scheduling
Given n jobs where every job has the following properties: Start TimeFinish TimeProfit or Value AssociatedThe task is to find the maximum profit in scheduling jobs such that no two jobs overlap. Examples: Input: jobs[][] = [[1, 2, 50], [3, 5, 20], [6, 19, 100], [2, 100, 200]]Output: 250Explanation:
9 min read
Count Derangements (Permutation such that no element appears in its original position)
A Derangement is a permutation of n elements, such that no element appears in its original position. For example, a derangement of [0, 1, 2, 3] is [2, 3, 1, 0].Given a number n, find the total number of Derangements of a set of n elements. Examples : Input: n = 2Output: 1Explanation: For two balls [
12 min read
Minimum insertions to form a palindrome
Given string str, the task is to find the minimum number of characters to be inserted to convert it to a palindrome. Examples: Input: str = abcdOutput: 3Explanation: Here we can append 3 characters in the beginning, and the resultant string will be a palindrome ("dcbabcd"). Input: str = abaOutput: 0
15+ min read
Ways to arrange Balls such that adjacent balls are of different types
There are 'p' balls of type P, 'q' balls of type Q and 'r' balls of type R. Using the balls we want to create a straight line such that no two balls of the same type are adjacent.Examples : Input: p = 1, q = 1, r = 0Output: 2Explanation: There are only two arrangements PQ and QP Input: p = 1, q = 1,
15+ min read
Hard problems on Dynamic programming
Palindrome Partitioning
Given a string s, the task is to find the minimum number of cuts needed for palindrome partitioning of the given string. A partitioning of the string is a palindrome partitioning if every sub-string of the partition is a palindrome. Examples: Input: s = "geek" Output: 2 Explanation: We need to make
15+ min read
Word Wrap Problem
Given an array arr[] of size n, where arr[i] denotes the number of characters in one word. Let k be the limit on the number of characters that can be put in one line (line width). Put line breaks in the given sequence such that the lines are printed neatly.Assume that the length of each word is smal
15+ min read
The Painter's Partition Problem
Given an array arr[] and k, where the array represents the boards and each element of the given array represents the length of each board. k numbers of painters are available to paint these boards. Consider that each unit of a board takes 1 unit of time to paint. The task is to find the minimum time
15+ min read
Program for Bridge and Torch problem
Given an array times[] of positive distinct integers denoting the crossing time of n people. These people are standing on one side of the bridge. There is only one torch with them and the bridge cannot be crossed without the torch. The bridge can hold at max two people at a time. When two people cro
15+ min read
Matrix Chain Multiplication
Given the dimension of a sequence of matrices in an array arr[], where the dimension of the ith matrix is (arr[i-1] * arr[i]), the task is to find the most efficient way to multiply these matrices together such that the total number of element multiplications is minimum. When two matrices of size m*
15+ min read
Printing brackets in Matrix Chain Multiplication Problem
Given an array arr[] which represents the chain of matrices such that the dimensions of the ith matrix are arr[i-1] x arr[i]. The task is to find the correct parenthesis of the matrices such that when we multiply all the matrices together, the cost or total number of element multiplications is minim
15+ min read
Maximum sum rectangle in a 2D matrix | DP-27
Given a 2D array, the task is to find the maximum sum sub-matrix in it. For example, in the following 2D array, the maximum sum sub-matrix is highlighted with green rectangle and sum of all elements in this sub-matrix is 29. This problem is mainly an extension of Largest Sum Contiguous Subarray for
15+ min read
Stock Buy and Sell - At-most k Transactions Allowed
In share trading, a buyer buys shares and sells on a future date. Given the stock price of n days, the trader is allowed to make at most k transactions, where a new transaction can only start after the previous transaction is complete, find out the maximum profit that a share trader could have made.
15+ min read
Minimum cost to sort strings using reversal operations of different costs
Given an array of strings and costs of reversing all strings, we need to sort the array. We cannot move strings in array, only string reversal is allowed. We need to reverse some of the strings in such a way that all strings make a lexicographic order and cost is also minimized. If it is not possibl
15+ min read
Count of AP (Arithmetic Progression) Subsequences in an array
Given an array arr[] of n positive integers. The task is to count the number of Arithmetic Progression subsequences in the array. Note: Empty sequence or single element sequence is Arithmetic Progression. Examples: Input: arr[] = [1, 2, 3]Output: 8Explanation: Arithmetic Progression subsequence from
15+ min read
Introduction to Dynamic Programming on Trees
Dynamic Programming is a technique to solve problems by breaking them down into overlapping sub-problems which follows the optimal substructure. There are various problems using DP like subset sum, knapsack, coin change etc. DP can also be applied to trees to solve some specific problems.Given a bin
13 min read
Maximum height of Tree when any Node can be considered as Root
Given a tree with n nodes and n-1 edges, the task is to find the maximum height of the tree when any node in the tree is considered as the root of the tree. Example: Input: Output: 5Explanation: The below diagram represents a tree with 11 nodes and 10 edges and the path that gives us the maximum hei
15+ min read
Longest repeating and non-overlapping substring
Given a string s, the task is to find the longest repeating non-overlapping substring in it. In other words, find 2 identical substrings of maximum length which do not overlap. Return -1 if no such string exists. Note: Multiple Answers are possible but we have to return the substring whose first occ
15+ min read
Top 20 Dynamic Programming Interview Questions
Dynamic Programming is an algorithmic paradigm that solves a given complex problem by breaking it into subproblems and stores the results of subproblems to avoid computing the same results again. Following are the most important Dynamic Programming problems asked in various Technical Interviews. Lon
1 min read