New 21 Game

MediumProbability DP · Sliding Window🧩 Probability DPLeetCode #837 ↗Updated

Problem

Alice starts with 0 points. While her total is below k, she draws a random integer from 1 to maxPts (uniformly, independently) and adds it. She stops as soon as her total reaches k or more. Return the probability that her final total is ≤ n.
Inputn = 10, k = 1, maxPts = 10Output1.00000
Inputn = 6, k = 1, maxPts = 10Output0.60000
Inputn = 21, k = 17, maxPts = 10Output0.73278

0 ≤ k ≤ n ≤ 104  ·  1 ≤ maxPts ≤ 104  ·  answers within 10-5 are accepted

Try it yourself

Java
class Solution {
    public double new21Game(int n, int k, int maxPts) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Let dp[x] be the chance of ever standing on exactly x points. It is (1/maxPts) × the sum of dp[j] over the previous maxPts totals j that were still < k (Alice only draws from those). That sum is a sliding window, so each dp[x] costs O(1).
PatternProbability DP

Instinct Asked for a probability or expected value after random moves? Run DP over (step, state) and split each state's mass across every outcome.

Memory hack Pour the probability like water - split it across the moves, let what spills off the board drain away, and the puddle that's left is your answer.

Open the Probability DP guide →

Approaches

Brute ForceRecursive Game Simulation

Time O(maxPtsk)Space O(k)

win(p) = 1 or 0 once p ≥ k (depending on p ≤ n); otherwise the average of win(p + d) for every draw d. It enumerates every possible sequence of draws.

Java
public double new21Game(int n, int k, int maxPts) {
    return win(0, n, k, maxPts);
}

private double win(int pts, int n, int k, int maxPts) {
    if (pts >= k) return pts <= n ? 1.0 : 0.0; // game over
    double sum = 0;
    for (int d = 1; d <= maxPts; d++) sum += win(pts + d, n, k, maxPts);
    return sum / maxPts;
}

A direct translation of the rules, only usable for tiny k.

At a glance

LevelApproachTimeSpace
Brute ForceRecursive Game SimulationO(maxPtsk)O(k)
BetterForward DP, Summing Each WindowO(n · maxPts)O(n)
OptimalSliding-Window DPO(n)O(n)
Common pitfalls
  • Adding dp[x] to the window when x ≥ k — Alice stopped there.
  • Forgetting k == 0: she never draws, so the answer is 1.
  • Subtracting dp[x - maxPts] even when that index was ≥ k (never added).
Interview tips
  • Define the DP state in words: “probability we ever hold exactly x points”.
  • Show the O(n·maxPts) version first, then spot the repeated window sum.
  • Explain why summing dp[k..n] is valid: stop events are mutually exclusive.
Pattern
Probability DP + sliding window sum → each state averages a fixed-width range of earlier states.
My notes saved in this browser