[LeetCode] New 21 Game

837. New 21 Game

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, W], where W is an integer. Each draw is independent and the outcomes have equal probabilities.

Alice stops drawing numbers when she gets K or more points. What is the probability that she has N or less points?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
double new21Game(int N, int K, int W) {
if(K == 0 || N >= K + W) return 1.0;
vector<double> dp(N + 1);
dp[0] = 1.0;
double res = 0.0, wSum = 1.0;
for(int i = 1; i <= N; i++) {
dp[i] = wSum / W;
if(i < K) {
wSum += dp[i];
} else {
res += dp[i];
}
if(i - W >= 0) wSum -= dp[i - W];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/04/07/PS/LeetCode/new-21-game/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.