Egg Drop With 2 Eggs and N Floors

medium dp math

Problem

You have two identical eggs and a building with n floors numbered 1 to n (1 ≤ n ≤ 1000). There is an unknown threshold floor f with 0 ≤ f ≤ n: any egg dropped from a floor above f breaks, while an egg dropped from floor f or below survives and can be dropped again.

Each move you drop one egg from a floor of your choice; a broken egg is gone for good. Return the minimum number of moves that guarantees you can determine f, no matter what its value is.

Inputn = 8
Output4
Three drops with two eggs can only separate 3 + 2 + 1 = 6 floors, so 8 floors need 4 drops (for example, first drops at floors 4 and 7, then a linear scan).

def two_egg_drop(n):
    # dp[i] = fewest worst-case drops with 2 eggs and i floors
    dp = [0] * (n + 1)
    for i in range(1, n + 1):
        best = float('inf')
        for x in range(1, i + 1):
            # break at x   -> scan the x-1 floors below, one egg left
            # survive at x -> i-x floors above, still two eggs
            cost = 1 + max(x - 1, dp[i - x])
            best = min(best, cost)
        dp[i] = best
    return dp[n]
function twoEggDrop(n) {
  // dp[i] = fewest worst-case drops with 2 eggs and i floors
  const dp = new Array(n + 1).fill(0);
  for (let i = 1; i <= n; i++) {
    let best = Infinity;
    for (let x = 1; x <= i; x++) {
      // break at x -> x-1 linear drops below; survive -> dp[i-x] above
      best = Math.min(best, 1 + Math.max(x - 1, dp[i - x]));
    }
    dp[i] = best;
  }
  return dp[n];
}
int twoEggDrop(int n) {
    // dp[i] = fewest worst-case drops with 2 eggs and i floors
    int[] dp = new int[n + 1];
    for (int i = 1; i <= n; i++) {
        int best = Integer.MAX_VALUE;
        for (int x = 1; x <= i; x++) {
            // break at x -> x-1 linear drops below; survive -> dp[i-x] above
            best = Math.min(best, 1 + Math.max(x - 1, dp[i - x]));
        }
        dp[i] = best;
    }
    return dp[n];
}
int twoEggDrop(int n) {
    // dp[i] = fewest worst-case drops with 2 eggs and i floors
    vector<int> dp(n + 1, 0);
    for (int i = 1; i <= n; i++) {
        int best = INT_MAX;
        for (int x = 1; x <= i; x++) {
            // break at x -> x-1 linear drops below; survive -> dp[i-x] above
            best = min(best, 1 + max(x - 1, dp[i - x]));
        }
        dp[i] = best;
    }
    return dp[n];
}
Time: O(n²) Space: O(n)