Post

867 New 21 Game

867 New 21 Game

New 21 Game image

Alice plays the following game, loosely based on the card game “21”.

Alice 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-5 of the actual answer are considered accepted.

 

Example 1:

1
2
3
4
5
**Input:** n = 10, k = 1, maxPts = 10
**Output:** 1.00000
**Explanation:** Alice gets a single card, then stops.

Example 2:

1
2
3
4
5
6
**Input:** n = 6, k = 1, maxPts = 10
**Output:** 0.60000
**Explanation:** Alice gets a single card, then stops.
In 6 out of 10 possibilities, she is at or below 6 points.

Example 3:

1
2
3
4
**Input:** n = 21, k = 17, maxPts = 10
**Output:** 0.73278

 

Constraints:

1
2
0 <= k <= n <= 104
1 <= maxPts <= 104
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

class Solution:
    def new21Game(self, n: int, k: int, maxPts: int) -> float:
        if k == 0 or n >= k + maxPts:
            return 1.0

        dp = [0.0] * (n + 1)
        dp[0] = 1.0
        window_sum = 1.0  # sum of last maxPts dp values
        result = 0.0

        for i in range(1, n + 1):
            dp[i] = window_sum / maxPts
            if i < k:  # still drawing
                window_sum += dp[i]
            else:  # stopped (≥k)
                result += dp[i]

            # shrink window
            if i - maxPts >= 0:
                window_sum -= dp[i - maxPts]

        return result




This post is licensed under CC BY 4.0 by the author.