Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Dynamic Programming

Egg Dropping Puzzle

Hard · Dynamic Programming · Asked at Google, Amazon, Microsoft, Goldman Sachs

You have k identical eggs and a building with n floors. There is a floor f (0 ≤ f ≤ n) such that an egg dropped from any floor above f breaks and from any floor at or below f does not. A broken egg cannot be used again; an unbroken one can. Print the minimum number of drops that guarantees finding f in the worst case.

Input

A single line with k and n.

Output

The minimum number of drops in the worst case.

Constraints

Turn it around: with m drops and k eggs you can cover at most F(m, k) = F(m − 1, k − 1) + F(m − 1, k) + 1 floors (the drop’s floor, plus what you can test below it if it breaks and above it if it does not). Increase m until F(m, k) ≥ n.

Example 1

Input

1 2

Output

2

Example 2

Input

2 6

Output

3

Example 3

Input

3 14

Output

4

Hints

  1. Asking "which floor to drop from" leads to an O(k · n²) DP. Ask the reverse question instead.
  2. With m drops and k eggs, how many floors can you always resolve?
  3. One drop splits the building: the part below (egg broke) and the part above (egg survived).

Approach

Let F(m, k) be the most floors you can handle with m drops and k eggs. The first drop happens at some floor: if the egg breaks you have m − 1 drops and k − 1 eggs for the floors below; if not, m − 1 drops and k eggs for the floors above. So F(m, k) = F(m − 1, k − 1) + F(m − 1, k) + 1. Increase m, updating a 1-D array for e = k down to 1, until F(m, k) ≥ n. With n ≤ 10^4 this takes at most n rounds (k = 1) and usually far fewer.

Complexity: O(k · answer) time · O(k) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    int k;
    long long n;
    cin >> k >> n;
    vector<long long> f(k + 1, 0);
    int m = 0;
    while (f[k] < n) {
        m++;
        for (int e = k; e >= 1; e--) f[e] = f[e] + f[e - 1] + 1;
    }
    cout << m << "\n";
    return 0;
}

Python solution

k, n = map(int, input().split())
f = [0] * (k + 1)
m = 0
while f[k] < n:
    m += 1
    for e in range(k, 0, -1):
        f[e] = f[e] + f[e - 1] + 1
print(m)

Java solution

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int k = sc.nextInt();
        long n = sc.nextLong();
        long[] f = new long[k + 1];
        int m = 0;
        while (f[k] < n) {
            m++;
            for (int e = k; e >= 1; e--) f[e] = f[e] + f[e - 1] + 1;
        }
        System.out.println(m);
    }
}

Solve Egg Dropping Puzzle online · All practice problems