I approached the New 21 Game problem using dynamic programming with a sliding window technique. I started by defining dp[i]
as the probability of having exactly i
points. Since Alice only continues drawing while her score is less than k
, I knew only those states could generate new outcomes. For each i
, the probability depends on the average of the previous maxPts
probabilities, but only from states less than k
. To avoid recalculating sums repeatedly, I maintained a running sliding window of these valid probabilities: I added the most recent one and removed the one that just went out of range. The result is then the sum of probabilities of terminal scores between k
and n
. Finally, I handled special cases: if k
is 0
or if n
is large enough (n >= k - 1 + maxPts
), the probability is guaranteed to be 1.0
.
class Solution: