Drop Eggs
There is a building ofnfloors. If an egg drops from the_k_th floor or above, it will break. If it's dropped from any floor below, it will not break.
You're given two eggs, Find_k_while minimize the number of drops for the worst case. Return the number of drops in the worst case.
Clarification
For n = 10, a naive way to find_k_is drop egg from 1st floor, 2nd floor ... kth floor. But in this worst case (k = 10), you have to drop 10 times.
Notice that you have two eggs, so you can drop at 4th, 7th & 9th floor, in the worst case (for example, k = 9) you have to drop 4 times.
Example
Given n =10, return4.
Given n =100, return14.
Solution 1: Similar to 2, only consider 1 dimension, Memory Limit Exceed
public int dropEggs(int n) {
if(n <= 0) {
return 0;
}
int[][] dp = new int[3][n + 1];
for(int i = 0; i <= 2; i++) {
dp[i][0] = 0;
dp[i][1] = 1;
}
for(int i = 0; i <= n; i++) {
dp[0][i] = 0;
dp[1][i] = i;
}
for(int i = 2; i <= 2; i++) {
for(int j = 2; j <= n; j++) {
dp[i][j] = Integer.MAX_VALUE;
for(int floor = 1; floor <= j; floor++) {
int worst = 1 + Math.max(dp[i - 1][floor - 1], dp[i][j - floor]);
if(dp[i][j] > worst) {
dp[i][j] = worst;
}
}
}
}
return dp[2][n];
}
Solution 2: A bit tricky. http://www.jiuzhang.com/qa/2711/
public int dropEggs(int n) {
if(n <= 0) {
return 0;
}
int i = 0, res = 0;
long sum = 0;
while(sum < n) {
i++;
res++;
sum += i;
}
return res;
}
Drop Egg II
There is a building ofnfloors. If an egg drops from thekth floor or above, it will break. If it's dropped from any floor below, it will not break.
You're givenmeggs, Find k while minimize the number of drops for the worst case. Return the number of drops in the worst case.
Have you met this question in a real interview?
Yes
Example
Givenm=2,n=100return14
Givenm=2,n=36return8
Sotution 1: The problem can be divide to two subproplems:
1. If egg in floor x break, then we need try from x - 1 floor with m - 1 eggs.
2. If egg in floor x not break, then we need try from x + 1 floor with m eggs.
We can implement this by recursion. This is time consuming if the floor is high. TLE.
public int dropEggs2(int m, int n) {
if(m == 1) {
return n;
}
if(n == 0 || n == 1) {
return n;
}
int res = Integer_MAX_VALUE;
for(int i = 2; i <= n; i++) {
//floor i consume 1, remember add it.
int worst = 1 + Math.max(dropEggs2(m - 1, i - 1), dropEggs2(m, n - i));
if (worst < res) {
res = worst;
}
}
return res;
}
Solution 2: DP. Reduce time complexity.
public int dropEggs2(int m, int n) {
if(m <= 0 || n <= 0) {
return 0;
}
int[][] dp = new int[m + 1][n + 1];
for(int i = 0; i <= m; i++) {
dp[i][0] = 0;
dp[i][1] = 1;
}
for(int i = 0; i <= n; i++) {
dp[0][i] = 0;
dp[1][i] = i;
}
for(int i = 2; i <= m; i++) {
for(int j = 2; j <= n; j++) {
dp[i][j] = Integer.MAX_VALUE;
int worst = 0;
for(int floor = 1; floor <= j; floor++) {
worst = 1 + Math.max(dp[i - 1][floor - 1], dp[i][j - floor]);
if(worst < dp[i][j]) {
dp[i][j] = worst;
}
}
}
}
return dp[m][n];
}