Problem. With eggs and a building of floors, find the highest floor from which an egg survives, minimizing the worst-case number of drops. A broken egg is lost; a surviving egg can be reused.
Invert the question: with eggs and drops, how many floors can be handled? Drop from floor : if it breaks, floors below remain with one egg less; otherwise floors above remain. So , whose solution is .
| Eggs | Answer |
|---|---|
| 1 | drops (linear scan from the bottom) |
| 2 | smallest with : 14 for 100 floors |
| binary search, | |
| general | binary search on with |
long long eggFloors(int eggs, long long drops) { // max floors decidable: sum_{i=1..eggs} C(drops, i), capped
long long s = 0, c = 1;
for (int i = 1; i <= eggs && i <= drops; i++) {
c = c * (drops - i + 1) / i; // exact: C(d, i) = C(d, i-1) * (d-i+1) / i
s += c; if (s >= (long long)4e18 || c >= (long long)4e18) return (long long)4e18;
}
return s;
}
long long minDrops(int eggs, long long floors) { // smallest d with eggFloors(eggs, d) >= floors
long long lo = 0, hi = floors;
while (lo < hi) { long long m = (lo + hi) / 2; if (eggFloors(eggs, m) >= floors) hi = m; else lo = m + 1; }
return lo;
}Proof: F(e, d) = sum of C(d, i)
The recurrence with is optimal: the first drop splits the floors into “below” (handled with eggs and drops) and “above” (with eggs and drops), and no strategy can handle more. Let . Then by Pascal’s rule, with the same boundary values. is increasing in , so the minimum is found by binary search. Tested against the classical DP for , .