KatInterview

Stop or Roll: Ten-Sided Die With a One-Time Reset

Dynamic ProgrammingAuto-graded · 24 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingexpected-valueoptimal-stopping

Last updated

Decide whether to stop or roll in a dice accumulation game where the first zero resets your total and the second zero wipes you out, using DP over (total, reset-used) states.

You are playing a solo dice game with a fair ten-sided die whose faces are 0, 1, 2, ..., 9, each equally likely. Rolls are independent.

You hold a running total. On each turn you must pick one of two actions:

  • stop: the game ends and you are paid exactly your current total in cash.
  • roll: roll the die once.
    • Faces 1 through 9 add that value to your total, and you then face the same choice again.
    • Face 0 depends on whether a zero has already been rolled earlier in this game:
      • If this is the first zero, your total is reset to 0 (nothing is banked) and the game continues. You may stop or roll again from 0.
      • If this is the second zero, the game ends immediately and you are paid 0.

Rolling costs nothing, and there is no limit on the number of rolls. Your goal is to maximize your expected cash payout.

Given the current total and whether the first zero has already happened, return the optimal action for that state.

Write a function that takes:

  • total: the current running total (an integer).
  • reset_used: True if the first zero has already occurred in this game, False otherwise.

Return the string "stop" if stopping now yields an expected payout at least as large as rolling (ties go to "stop"). Otherwise return "roll".

Constraints

  • 0 <= total <= 1000
  • reset_used is a boolean.
  • The objective is expected payout, not the probability of reaching a target.
  • A reset does not bank the previous total, and you are allowed to stop immediately after a reset (with a total of 0).
  • Both optimal play from every future state and the tie-breaking rule (stop when equal) must be used.

Examples

Example 1

Input: best_move(0, False)

Output: 'roll'

Example 2

Input: best_move(10, False)

Output: 'roll'

Example 3

Input: best_move(0, True)

Output: 'roll'

Example 4

Input: best_move(10, True)

Output: 'roll'

Hints

Hint 1

The right state is the pair (total, whether a zero has already happened). Solve the 'zero already happened' case first, since it never depends on the other case.

Hint 2

In the 'zero already happened' case, rolling a 0 pays 0. For large totals stopping beats rolling, so you can compute values downward from a large cap: value(t) = max(t, average over the ten faces of the next values).

Hint 3

In the 'no zero yet' case, rolling a 0 does not end the game: it leads to the value of total 0 in the 'zero already happened' world. Plug that constant in, run the same downward DP, and compare stopping with rolling at the queried total.