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 are uniformly distributed.
Alice stops drawing numbers when she gets k
or more points. Return the probability that Alice has n
or fewer points.
n
, k
, and maxPts
:
k
is 0? In this case, Alice doesn’t draw any cards, and the probability will depend on whether 0 ≤ n.maxPts
is 1? It may reduce the problem to a simpler scenario.dp[i]
be the probability of having i
points after some number of draws.dp[0] = 1.0
because we start with 0 points.maxPts
scores, reducing the complexity of computing the sum repeatedly.i
from 1 to n
, dp[i]
is computed based on the sliding window sum.i
is less than k
, update the sliding window.i
points where k ≤ i ≤ n
.#include <vector>
using namespace std;
class Solution {
public:
double new21Game(int n, int k, int maxPts) {
if (k == 0 || n >= k + maxPts) return 1.0;
vector<double> dp(n + 1);
dp[0] = 1.0;
double windowSum = 1.0;
double result = 0.0;
for (int i = 1; i <= n; ++i) {
dp[i] = windowSum / maxPts;
if (i < k) {
windowSum += dp[i];
} else {
result += dp[i];
}
if (i >= maxPts) {
windowSum -= dp[i - maxPts];
}
}
return result;
}
};
This approach effectively computes the probability that Alice’s score is less than or equal to n
after stopping the draws using a dynamic programming approach combined with sliding window technique.
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?