Problem. You have identical eggs and a building with floors. There is a threshold floor : an egg dropped from floor or below survives; above it breaks. A broken egg cannot be reused. In the worst case, what is the minimum number of drops needed to determine exactly?
The naive DP β
Dropping from floor : if the egg breaks, eggs remain and floors below; if it survives, eggs and floors above.
int eggDrop(int k, int n) {
vector<vector<int>> dp(k + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= n; i++) dp[1][i] = i; // one egg: linear scan
for (int e = 2; e <= k; e++)
for (int f = 1; f <= n; f++) {
dp[e][f] = INT_MAX;
for (int x = 1; x <= f; x++)
dp[e][f] = min(dp[e][f], 1 + max(dp[e-1][x-1], dp[e][f-x]));
}
return dp[k][n];
}The inverted DP β , and it is the better formulation
Flip the question: with eggs and drops, how many floors can I distinguish?
The first term counts the floors below (egg broke), the second the floors above (egg survived), and the is the floor tested. Increase until .
int eggDropFast(int k, int n) {
vector<int> f(k + 1, 0);
int t = 0;
while (f[k] < n) {
t++;
for (int e = k; e >= 1; e--) f[e] = f[e] + f[e-1] + 1; // in place, downward
}
return t;
}with for β effectively instant.
The closed form
so the answer is the smallest with .
Why: a strategy is a decision tree of depth in which each root-to-leaf path uses at most βbreakβ branches. The number of such paths is exactly the number of binary strings of length with at most ones.
Special cases
| Answer | |
|---|---|
| 1 | (linear scan from the bottom) |
| 2 | smallest with , i.e. |
| β plain binary search |
The two-egg case is the famous one: for the answer is 14, achieved by first dropping from floor 14, then 27, then 39, β¦ (decreasing gaps), not from floor 50.
The decreasing-gap structure is the point: each failed drop costs one egg and one attempt, so the next interval must be one shorter.
The technique it teaches
When a DPβs answer range is small but its state space is large, invert it β make the answer an index and the state a value.
Here, βminimum drops for floorsβ ( states, transitions) becomes βmaximum floors with dropsβ ( values of , transitions). The same inversion turns the knapsack into when the values are small, and is worth checking on any DP with an awkward dimension.
Variants
- Minimise the expected drops (rather than the worst case) β a different DP, over probability distributions.
- Eggs of different fragility β each has its own threshold.
- eggs, exactly drops, count the strategies β the binomial sum above.
- Adversarial floors β the standard version already assumes an adversary chooses .
See also: Introduction to DP Β· Binary Search Β· Combinatorics