KatInterview

Bayesian Guessing Game with Unknown Coin Bias

Arrays & HashingAuto-graded · 24 test cases
MediumAuto-gradedArrays & Hashingprobabilitybayesianexpected-value

Last updated

Compute expected optimal winnings when sequentially guessing coin flips with a uniform-prior unknown bias.

A coin is flipped n times in a row. The probability of Heads is an unknown value p; before any flips occur, p is drawn once from a Uniform(0, 1) distribution and then stays fixed for the entire sequence.

Before each flip you must commit to guessing either Heads or Tails, and you see the actual outcome only after your guess. Every correct guess earns you $1; every incorrect guess earns you $0.

You may choose each guess adaptively, based on the outcomes of all previous flips (and therefore on your running count of Heads and Tails).

Given n, return the maximum possible expected total winnings over the whole sequence of n flips, when you follow the guessing policy that maximizes expected total reward. Report the answer as a float.

Task: implement a function that, given n, returns that maximum expected total winnings.

Constraints

  • 1 <= n <= 1000
  • p is drawn once from Uniform(0, 1) and is fixed for all n flips (not re-drawn per flip).
  • Guesses may depend on all previously observed outcomes.
  • A correct guess pays exactly 1, an incorrect guess pays exactly 0.
  • Return value is a floating-point number (no specific precision required beyond what the reference produces).

Examples

Example 1

Input: max_expected_winnings(1)

Output: 0.5

Example 2

Input: max_expected_winnings(2)

Output: 1.1666666666666665

Example 3

Input: max_expected_winnings(10)

Output: 6.833621933621934

Example 4

Input: max_expected_winnings(100)

Output: 73.77863732823776

Hints

Hint 1

With a Uniform(0,1) prior, after seeing h heads and t-h tails, the posterior predictive probability of Heads is (h+1)/(t+2).

Hint 2

Before any flip the total number of Heads is equally likely to be any value in {0, 1, ..., t}, so you can average the best achievable one-step reward over that uniform distribution.

Hint 3

At step t the optimal expected reward is the larger of the two posterior-predictive probabilities; sum that over all steps.