Break-Even Fee for Four-Chest Prize Search
Medium · Statistics & Math · Data Scientist · Technical Screen
Problem Statement
Four sealed chests are arranged in front of a contestant. Exactly one chest holds a cash payout worth prize, while the other three are empty, and all four chests have an equal 1/4 chance of holding the payout.
Inspecting any closed chest requires paying a fixed entry charge c beforehand—even when only a single closed chest remains. Play stops immediately if the contestant uncovers the payout. Whenever an inspected chest turns out to be empty, the contestant may either walk away with no further charges or pay c again to inspect another closed chest.
Implement price_four_box_game(prize: float) -> Dict[str, object] to compute two quantities under risk-neutral, expected-profit-maximizing play:
"break_even_fee": the maximum per-chest chargecat which entering the game (inspecting at least one chest) yields a nonnegative expected net profit (>= 0)."continue_after_first_failure": a boolean (TrueorFalse) indicating whether a contestant who already paidc = break_even_feeto inspect a first chest and found it empty should paycto inspect a second chest. Because the initial payment is already spent and unrecoverable, evaluate this choice strictly on conditional future expected profit across the remaining three chests (Truewhen optimal future expected profit is>= 0, andFalseotherwise).
def price_four_box_game(prize: float) -> Dict[str, object]:
Examples
Example 1
Input: prize = 250
Output: {"break_even_fee": 100.0, "continue_after_first_failure": True}
Explanation: Because every empty chest improves the win odds on subsequent chests (1/4, then 1/3, then 1/2, then 1), the best strategy inspects chests until the payout appears. Across the four equally likely chest positions, this takes (1 + 2 + 3 + 4) / 4 = 2.5 inspections on average, so 250 - 2.5 * c = 0 gives c = 100.0. If the first chest is empty, three chests remain and finding the payout takes (1 + 2 + 3) / 3 = 2.0 future inspections on average, yielding 250 - 2.0 * 100.0 = +50.0 >= 0 in expected future profit, so continuing is optimal (True).
Example 2
Input: prize = 75
Output: {"break_even_fee": 30.0, "continue_after_first_failure": True}
Explanation: Dividing 75 by the 2.5 expected inspections gives a break-even charge of 30.0. After an empty first chest, continuing over the three remaining chests has conditional future expected profit 75 - 2.0 * 30.0 = +15.0 >= 0, so the contestant continues.
Example 3
Input: prize = 12.5
Output: {"break_even_fee": 5.0, "continue_after_first_failure": True}
Explanation: At c = 12.5 / 2.5 = 5.0, starting from four closed chests breaks even in expectation, and conditional future profit after one empty chest is 12.5 - 2.0 * 5.0 = +2.5 >= 0.
Constraints
0 <= prize <= 10^9(prizemay be anintorfloat).- Return a dictionary with exact keys
"break_even_fee"(intorfloat, checked within10^-6relative/absolute tolerance) and"continue_after_first_failure"(bool).
Step-by-step walkthrough
Understand the game rules and hidden assumptions
Four sealed chests sit in front of a contestant. One chest holds a payout
P(for instance,P = 250in Example 1), and the other three chests are empty. Inspecting any closed chest costs the same chargec. We need to return a dictionary with two answers:break_even_fee: the largest chargecat which an optimal contestant starting from 4 closed chests has an expected value (the long-run average profit across repeated plays) greater than or equal to0.continue_after_first_failure: a boolean (TrueorFalse) telling whether a contestant who paidbreak_even_fee, inspected the first chest, and found it empty should keep going.
Before doing any algebra, let us pin down three rules of the setup:
- Uncovering the payout halts play immediately. Once you claim
P, there is no reason to paycto inspect empty chests. - Every inspection costs
c, even the final chest. If the first three chests are empty, you know with certainty that chest 4 holds the payout, yet opening chest 4 still costsc. - Past charges are sunk costs. A sunk cost is money already spent that cannot be recovered regardless of future choices. After missing on chest 1, walking away leaves you at
-c, so the continuation choice compares only future expected payout against future charges.
Why pricing only the first chest falls short
A tempting first guess looks only at the very first inspection: it wins
Pwith probability1/4, soP / 4 - c = 0givesc = 0.25 * P(62.5whenP = 250).Why is
62.5too low? Because finding an empty chest is not a total loss—it eliminates an empty chest and improves your odds on every remaining chest while the per-chest chargecstays fixed:Chests left: 4 chests --> 3 chests --> 2 chests --> 1 chest Win chance: 1/4 1/3 1/2 1/1 (certain!) Cost to open: c c c cPaying
cfor the first chest buys both a1/4shot atPright now and the option to take much stronger bets (1/3,1/2,1/1) if you miss.Price all four stopping plans from scratch
Because all closed chests are equally likely to hold the payout, the order in which you pick chests does not matter. The only real choice is how many chests
k(1,2,3, or4) you are willing to inspect before walking away (always stopping immediately upon finding the payout).Suppose the payout sits equally likely in position 1, 2, 3, or 4 of your inspection order. Let us count how many chests each plan
kinspects across those 4 equally likely cases (shown withP = 250in parentheses):Plan k Inspections if payout is in... Average inspections Win prob Expected profit Break-even c pos 1 pos 2 pos 3 pos 4 k = 1 1 1 1 1 (1+1+1+1)/4 = 1.00 1/4 0.25 P - 1.00 c 0.250 P (62.50) k = 2 1 2 2 2 (1+2+2+2)/4 = 1.75 2/4 0.50 P - 1.75 c 0.286 P (71.43) k = 3 1 2 3 3 (1+2+3+3)/4 = 2.25 3/4 0.75 P - 2.25 c 0.333 P (83.33) k = 4 1 2 3 4 (1+2+3+4)/4 = 2.50 4/4 1.00 P - 2.50 c 0.400 P (100.00)For each plan
k, settingExpected profit = 0givesc = (Win prob * P) / (Average inspections). Notice whyk = 4(continuing until the payout appears) tolerates the highest charge: any plan that quits early pays for the worst1/4bet and then walks away right before the1/2and1/1bets!With
BOXES = 4, the full plan (k = 4) inspects(1 + 2 + 3 + 4) / 4 = (BOXES + 1) / 2 = 2.5chests on average and collectsPevery time:P - 2.5 * c = 0 ==> c = P / 2.5 = 0.4 * PFor
P = 250, the break-even charge is100.0.Compute future value with backward induction
To evaluate what play is worth from any count of unopened chests
boxes_left, we use backward induction—working from the last chest backward to the start:- Base case (
boxes_left == 1): Only one closed chest remains, so the payout is guaranteed to be inside. Opening it collectsprizeand costsfee, yieldingprize - fee. - Step (
boxes_left > 1): Payingfeeto open one chest right now uncovers the payout with probability1 / boxes_left(winningprize) and misses with probability(boxes_left - 1) / boxes_left. On a miss,boxes_left - 1chests remain, and an optimal contestant takes the better of walking away (0.0) or continuing (value_if_miss).
Let us trace
P = 250andfee = 100from 1 chest up to 4 chests:boxes_left = 1: 250 - 100 = +150.0 (certain win of 250 for fee 100) boxes_left = 2: (1/2)*250 - 100 + (1/2)*max(0, 150) = +100.0 (125 - 100 + 75) boxes_left = 3: (1/3)*250 - 100 + (2/3)*max(0, 100) = +50.0 (83.33 - 100 + 66.67) boxes_left = 4: (1/4)*250 - 100 + (3/4)*max(0, 50) = 0.0 (62.50 - 100 + 37.50 -> exact break-even!)Notice how
boxes_left = 4evaluates to0.0, confirming that100.0is the exact break-even charge. Here isvalue_of_openingin code:def value_of_opening(prize: float, fee: float, boxes_left: int) -> float: """Expected future profit of paying `fee` to open one box now and playing optimally after. `boxes_left` is the count of unopened boxes (e.g., 4 at start, 3 after one miss), with the prize equally likely to be inside each unopened box. """ # Base case: with 1 closed box left, the prize is guaranteed to be inside, # but the player must still pay `fee` to open that final box and claim `prize`. if boxes_left == 1: return prize - fee # Phase 1: compute optimal future value if this opening misses (boxes_left - 1 remain). # After a miss, the player can either walk away (0.0 future profit) or keep opening. value_if_miss = value_of_opening(prize, fee, boxes_left - 1) best_after_miss = max(0.0, value_if_miss) # Phase 2: combine the immediate fee with the expected payoff from hitting or missing now. hit_probability = 1.0 / boxes_left miss_probability = (boxes_left - 1) / boxes_left expected_future_profit = hit_probability * prize - fee + miss_probability * best_after_miss return expected_future_profit- Base case (
Decide whether to continue after the first failure
Now suppose you paid
break_even_fee = 100.0, opened chest 1, and found it empty. Should you continue?Look at the
boxes_left = 3row in our trace above: from this point onward, playing optimally across the 3 remaining chests has a conditional future expected profit of+50.0(in general,+0.2 * P), whereas walking away gives0.0future profit.Why do people get tripped up here? Because if you add back the
-100already spent, your overall net result if you continue is-100 + 50 = -50, which looks like a loss! Yet if you quit right now, your overall net result is-100, which is worse (-50 > -100). Because the initial100is gone either way, comparing future expected profit (+50 >= 0) gives the right answer:True(continue).BOXES = 4 def price_four_box_game(prize: float) -> Dict[str, object]: # Phase 1: compute the break-even fee at the start of the game. # Because win odds improve after every miss (1/4 -> 1/3 -> 1/2 -> 1), the best plan # opens boxes until the prize appears, taking (1 + 2 + 3 + 4) / 4 = 2.5 openings on average. average_openings = (BOXES + 1) / 2 break_even_fee = prize / average_openings # Phase 2: decide whether to continue after paying `break_even_fee` once and missing. # The first fee is a sunk cost, so compare only future profit on the remaining 3 boxes # against 0.0 (using >= 0.0 to match the nonnegative expected-value rule). future_value_after_miss = value_of_opening(prize, break_even_fee, BOXES - 1) should_continue = future_value_after_miss >= 0.0 # Output dictionary shape: {"break_even_fee": float, "continue_after_first_failure": bool} return { "break_even_fee": break_even_fee, "continue_after_first_failure": should_continue, }Verify on Example 1 (`prize = 250`)
Let us double-check both outputs by listing every equally likely outcome at
fee = 100:From the start (4 chests, each equally likely with probability 1/4): - Payout in chest 1: pay 100, win 250 --> net +150 - Payout in chest 2: pay 200, win 250 --> net +50 - Payout in chest 3: pay 300, win 250 --> net -50 - Payout in chest 4: pay 400, win 250 --> net -150 Average from start = (+150 + 50 - 50 - 150) / 4 = 0 (breaks even!) After chest 1 is empty (3 chests left, each equally likely with probability 1/3): - Payout in chest 2: pay 100 more, win 250 --> future +150 (total +50) - Payout in chest 3: pay 200 more, win 250 --> future +50 (total -50) - Payout in chest 4: pay 300 more, win 250 --> future -50 (total -150) Average future profit = (+150 + 50 - 50) / 3 = +50 > 0 --> continue = True!Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple # Total number of boxes in the game; exactly one box holds the prize. BOXES = 4 def value_of_opening(prize: float, fee: float, boxes_left: int) -> float: """Expected future profit of paying `fee` to open one box now and playing optimally after. `boxes_left` is the count of unopened boxes (e.g., 4 at start, 3 after one miss), with the prize equally likely to be inside each unopened box. """ # Base case: with 1 closed box left, the prize is guaranteed to be inside, # but the player must still pay `fee` to open that final box and claim `prize`. if boxes_left == 1: return prize - fee # Phase 1: compute optimal future value if this opening misses (boxes_left - 1 remain). # After a miss, the player can either walk away (0.0 future profit) or keep opening. value_if_miss = value_of_opening(prize, fee, boxes_left - 1) best_after_miss = max(0.0, value_if_miss) # Phase 2: combine the immediate fee with the expected payoff from hitting or missing now. hit_probability = 1.0 / boxes_left miss_probability = (boxes_left - 1) / boxes_left expected_future_profit = hit_probability * prize - fee + miss_probability * best_after_miss return expected_future_profit def price_four_box_game(prize: float) -> Dict[str, object]: # Phase 1: compute the break-even fee at the start of the game. # Because win odds improve after every miss (1/4 -> 1/3 -> 1/2 -> 1), the best plan # opens boxes until the prize appears, taking (1 + 2 + 3 + 4) / 4 = 2.5 openings on average. average_openings = (BOXES + 1) / 2 break_even_fee = prize / average_openings # Phase 2: decide whether to continue after paying `break_even_fee` once and missing. # The first fee is a sunk cost, so compare only future profit on the remaining 3 boxes # against 0.0 (using >= 0.0 to match the nonnegative expected-value rule). future_value_after_miss = value_of_opening(prize, break_even_fee, BOXES - 1) should_continue = future_value_after_miss >= 0.0 # Output dictionary shape: {"break_even_fee": float, "continue_after_first_failure": bool} return { "break_even_fee": break_even_fee, "continue_after_first_failure": should_continue, }✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a packet of 4 scratch-off cards where exactly one card pays 250 and the other three pay nothing. Every time you scratch a blank card, you eliminate a dud from the packet, so the remaining cards become much more likely to win (1/4, then 1/3, then 1/2, then a guaranteed 1/1) while the per-card charge c stays fixed. Because the odds improve after every blank card, an optimal contestant never quits partway through—if the game is worth starting at charge c, the remaining cards are even more favorable after a miss.
A naive calculation prices only the very first chest (250 / 4 = 62.5), overlooking that opening chest 1 also buys access to the richer 1/3, 1/2, and 1/1 draws whenever chest 1 is empty. A second classic trap strikes after chest 1 misses: subtracting the 100 already spent makes continuing look like a -50 net loss overall, forgetting that the initial 100 is a sunk cost (money already spent that cannot be recovered) and quitting immediately locks in an even steeper -100 loss.
Let us trace Example 1 with prize = 250:
- Across the 4 equally likely payout positions, inspecting until you win takes
1,2,3, or4inspections—an expected value (long-run average outcome) of(1 + 2 + 3 + 4) / 4 = 2.5inspections—and always collects250. Solving250 - 2.5 * c = 0givesbreak_even_fee = 100.0. - Using backward induction (working from the final decision step backward to earlier steps), if chest 1 is empty at
c = 100.0, 3 chests remain (1,2, or3additional inspections, averaging2.0future inspections). Expected future profit from continuing is250 - 2.0 * 100.0 = +50.0, which beats walking away (0.0), socontinue_after_first_failureisTrue.
Complexity
- Time:
O(1)because the chest count is fixed at4, so computing the closed-form break-even charge takes one division andvalue_of_openingexecutes3recursive steps. Generalized tomcontainers,2 * prize / (m + 1)still takesO(1)arithmetic operations, whilevalue_of_openingvisits each count fromm - 1down to1once inO(m)time. - Space:
O(1)because we keep only scalar numbers and booleans, and the recursion stack reaches depth3. Formcontainers, the recursive helper usesO(m)call-stack frames, which an iterative bottom-up loop from1tom - 1reduces toO(1).
Edge cases
- Linear scaling for all positive payouts: Both
break_even_fee = 0.4 * prizeand the conditional future profit after one miss (0.2 * prize) scale directly withprize, socontinue_after_first_failureevaluates toTruefor everyprize > 0, from1000000down to0.001. - Paying to open the fourth chest: After 3 empty chests, you know for sure that chest 4 holds the payout, yet you still pay
cto unlock it (value_of_opening(prize, fee, 1) = prize - fee). If the last chest could be claimed without payingc, average inspections would shrink to(1 + 2 + 3 + 3) / 4 = 2.25and the break-even charge would rise toprize / 2.25 ≈ 0.444 * prize. - Zero payout (
prize = 0): The break-even charge is0.0and conditional future profit after one miss is0.0. Because breaking even permits nonnegative (>= 0.0) expected profit,continue_after_first_failureisTrue. - Floating-point rounding near zero: At
boxes_left = 4, evaluatingvalue_of_opening(prize, break_even_fee, 4)in floating-point math can introduce tiny rounding noise around0(such as-1e-16 * prize). Atboxes_left = 3, however, conditional future profit is+0.2 * prize, safely above zero for allprize > 0.
Common mistakes
- Pricing only the first inspection (
0.25 * prize): Solvingprize / 4 - c >= 0treats the setup as a single-try lottery and ignores the option to keep inspecting at better odds. - Miscounting average inspections: Guessing
4 / 2 = 2inspections (giving0.5 * prize) forgets that1, 2, 3, 4averages to2.5, while(1 + 2 + 3 + 3) / 4 = 2.25mistakenly assumes the final chest is free to open. - Counting the sunk first charge in the continuation check: Adding the already-spent
-100to the+50future gain produces-50 < 0and wrongly advises quitting, even though quitting leaves the contestant at-100rather than-50. - Wrapping the 4-chest starting value in
max(0, ...)when solving forc: Allowing "inspect 0 chests for0profit" makes expected profit>= 0at arbitrarily huge charges because the contestant simply declines to start. Entering the game requires inspecting at least one chest.
Alternative approaches
Numerical root-finding with bisection. Bisection is binary search over a continuous interval [low, high] to locate where a monotonic function crosses zero. Because value_of_opening(prize, c, 4) decreases strictly and continuously with c (+prize at c = 0 and negative at c = prize), repeatedly halving [0, prize] pinpoints the break-even charge without deriving a closed-form average. That numerical method generalizes effortlessly when inspection charges vary by chest or prior probabilities are non-uniform.
Follow-up questions
- How do the break-even cost and continuation choice change when there are
mcontainers instead of four? Under the commit-to-finish plan, the number of inspections is uniformly distributed across1, 2, ..., m, giving an average of(1 + 2 + ... + m) / m = (m + 1) / 2inspections. Any partial plan that halts after at mostkchests breaks even atP / (m - (k - 1) / 2), which increases withkand peaks atk = m, yieldingbreak_even_fee = 2 * P / (m + 1). After an empty first container,m - 1containers remain and finishing averagesm / 2future inspections, so conditional future profit isP - (m / 2) * (2 * P / (m + 1)) = P / (m + 1) > 0—meaning a rational contestant still continues for everym >= 2andP > 0. - How does the optimal strategy shift if the reward is placed in different containers with non-uniform probabilities? You should always inspect containers in descending order of prior win probability (
p_1 >= p_2 >= ... >= p_m), because checking likelier containers earlier collects the reward sooner and avoids paying subsequent charges; after each miss, Bayes' rule (rescaling each remaining probability by dividing by the total remaining probability mass) multiplies every unopened container's probability by the same constant, preserving that exact priority order. LettingF_k = p_1 + ... + p_kdenote the cumulative win chance across the topkcontainers, stopping after at mostkinspections wins with probabilityF_kand pays for1 + (1 - F_1) + ... + (1 - F_{k-1})expected inspections, so the break-even charge ismax_{1 <= k <= m} (P * F_k / E[inspections_k]). Unlike uniform priors, an early-stopping plan can now beat inspecting allmcontainers and flipcontinue_after_first_failuretoFalse: for instance, with probabilities(0.9, 1/30, 1/30, 1/30), inspecting only container 1 breaks even at0.9 * P(above the full plan'sP / 1.2 ≈ 0.833 * P), and if container 1 is empty, the three1/30containers break even at just0.5 * P < 0.9 * P, so walking away immediately is optimal.
Follow-up questions
- How do the break-even cost and continuation choice change when there are `m` containers instead of four?
- How does the optimal strategy shift if the reward is placed in different containers with non-uniform probabilities?
Similar questions
- Expected Count of Strict Running Maxima
- OOP vs. Functional Python Enrichment Pipelines
- Distinct Coin Combinations for a Target Sum
- Handling an Inconclusive A/B Test Readout
- Ad Serving Economics, Mixture Variance, and Waiting Times
- Target Bankroll Probability with Biased Flips