Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Super Egg Drop in C++
Suppose we have given K eggs, and we have a building with N floors from 1 to N. Now each egg is identical in function, and if an egg breaks, we cannot drop it again.
There exists a floor F with between 0 and N such that any egg dropped at a floor higher than F will break, and any egg dropped at or below floor F will not break. In each move, we may take an egg and drop it from any floor X. The X is in range 1 to N.
Our goal is to know with certainty what the value of F is. So, what will be the minimum number of moves that we need to know with certainty what F is, regardless of the initial value of F?
So, if the input is like K = 2 and N = 6, then the output will be 3.
To solve this, we will follow these steps −
Define one 2D array dp
Define a function solve(), this will take K, N,
-
if N <= 1, then −
return N
-
if K is same as 1, then −
return N
-
if dp[K, N] is not equal to -1, then −
return dp[K, N]
-
ret := N, low := 0, high := N
while low <= high, do −
left := 1 + solve(K - 1, mid - 1)
right := 1 + solve(K, N - mid)
ret := minimum of ret and maximum of left and right
-
if left is same as right, then −
Come out from the loop
-
if left < right, then:
low := mid + 1
otherwise high := mid - 1
return dp[K, N] = ret
Frm the main method do the following −
dp := Create one 2D array (K + 1) x (N + 1), fill this with -1
return solve(K, N)
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> dp;
int solve(int K, int N) {
if (N <= 1)
return N;
if (K == 1)
return N;
if (dp[K][N] != -1)
return dp[K][N];
int ret = N;
int low = 0;
int high = N;
while (low <= high) {
int mid = low + (high - low) / 2;
int left = 1 + solve(K - 1, mid - 1);
int right = 1 + solve(K, N - mid);
ret = min(ret, max(left, right));
if (left == right)
break;
if (left < right) {
low = mid + 1;
} else
high = mid - 1;
}
return dp[K][N] = ret;
}
int superEggDrop(int K, int N) {
dp = vector<vector<int>>(K + 1, vector<int>(N + 1, -1));
return solve(K, N);
}
};
main(){
Solution ob;
cout << (ob.superEggDrop(2,6));
}
Input
2, 6
Output
3