Leetcode Problem 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 each draw is independent and the probability of getting any integer within the range [1, W]
is equal. Alice stops drawing numbers when she gets K
or more points. Alice wins if her points are anywhere from K
to N
inclusive.
Given the integers N
, K
, and W
, return the probability that Alice wins the game.
K
.0 ≤ K ≤ N ≤ 10^4
and 1 ≤ W ≤ 10^4
.K
where Alice starts drawing points?
K
points.K
points.dp
where dp[i]
represents the probability of having exactly i
points.dp[0]
is 1 because Alice starts with 0 points.K-1
, calculate the probabilities for every future point Alice could get by drawing 1 to W
points.i
from K
to N
, sum probabilities from dp[i]
to get the final result.public class Solution {
public double new21Game(int N, int K, int W) {
if (K == 0 || N >= K + W) {
return 1.0;
}
double[] dp = new double[N + 1];
double sum = 1.0; // This will store the sum of probabilities in the window
dp[0] = 1.0;
double result = 0.0;
for (int i = 1; i <= N; i++) {
dp[i] = sum / W;
if (i < K) {
sum += dp[i];
} else {
result += dp[i];
}
if (i - W >= 0) {
sum -= dp[i - W];
}
}
return result;
}
}
i
from 1 to N
and maintain the sliding window sum which ensures each operation within the loop is O(1).dp
of size N + 1
to store the probabilities.This approach ensures we efficiently calculate the probability of Alice winning the game with the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?