Alice plays a game loosely based on the card game 21. She starts with 0 points and draws numbers while she has less than k points.

During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities.

Alice stops drawing numbers when she gets k or more points. Return the probability that Alice has n or fewer points.

Answers within 10⁻⁵ of the actual answer are considered accepted.

Input & Output

Example 1 — Basic Case
$ Input: n = 21, k = 17, maxPts = 10
Output: 0.73278
💡 Note: Alice draws until reaching 17+ points. She needs to end with ≤21 points. Most outcomes from 17-26 points are ≤21, giving high probability.
Example 2 — Edge Case
$ Input: n = 6, k = 1, maxPts = 10
Output: 0.60000
💡 Note: Alice stops after first draw (≥1 point). Draws 1-6 are valid (6 outcomes), draws 7-10 exceed n (4 outcomes). Probability = 6/10 = 0.6.
Example 3 — Guaranteed Win
$ Input: n = 21, k = 17, maxPts = 3
Output: 1.00000
💡 Note: From any score 14-16, Alice draws 1-3 points, reaching 17-19. All outcomes ≤21, so probability is 1.0.

Constraints

  • 0 ≤ k ≤ n ≤ 104
  • 1 ≤ maxPts ≤ 104

Visualization

Tap to expand
New 21 Game - Dynamic Programming INPUT Alice's Game Start: 0 points Draw until points >= k 1-10 Random Draw n = 21 max points k = 17 stop point maxPts = 10 draw range P(each draw) = 1/10 Find P(final <= 21) ALGORITHM STEPS 1 Define DP State dp[i] = P(reach i points) 2 Base Case dp[0] = 1 (start at 0) 3 Transition dp[i] = sum(dp[i-j])/maxPts for j in [1, maxPts] 4 Sliding Window Optimize with window sum DP Array (partial) 1.0 i=0 .1 i=1 .11 i=2 ... .073 i=21 Result = sum(dp[k]...dp[n]) FINAL RESULT 73.28% Probability of success Game Outcomes WIN 17-21 pts 73.28% LOSE 22-26 pts 26.72% OUTPUT 0.73278 OK - Accepted Within 10^-5 tolerance Key Insight: Use sliding window DP to compute probabilities efficiently. For each state i < k, Alice can reach states [i+1, i+maxPts]. Maintain window sum W = sum(dp[i-maxPts]...dp[i-1]) where i < k. Time: O(n), Space: O(n). Sum dp[k] to dp[n] for final probability of ending with <= n points. TutorialsPoint - New 21 Game | Dynamic Programming with Sliding Window
Asked in
Google 15 Amazon 8 Microsoft 6
28.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen