classSolution{public:doublenew21Game(intn,intk,intmaxPts){// When the game ends, the point is in [k..k - 1 + maxPts]// P = 1, if n >= k - 1 + maxPts// P = 0, if n < k (note the constraints already have k <= n)if(k==0||n>=k-1+maxPts)return1.0;doubleans=0.0;vector<double>dp(n+1);// dp[i] := prob to have i pointsdp[0]=1.0;doublewindowSum=dp[0];// P(i - 1) + P(i - 2) + ... + P(i - maxPts)for(inti=1;i<=n;++i){// The prob to get point i is// P(i) = [P(i - 1) + P(i - 2) + ... + P(i - maxPts)] / maxPtsdp[i]=windowSum/maxPts;if(i<k)windowSum+=dp[i];else// The game endsans+=dp[i];if(i-maxPts>=0)windowSum-=dp[i-maxPts];}returnans;}};
classSolution{publicdoublenew21Game(intn,intk,intmaxPts){// When the game ends, the point is in [k..k - 1 + maxPts]// P = 1, if n >= k - 1 + maxPts// P = 0, if n < k (note the constraints already have k <= n)if(k==0||n>=k-1+maxPts)return1.0;doubleans=0.0;double[]dp=newdouble[n+1];// dp[i] := prob to have i pointsdp[0]=1.0;doublewindowSum=dp[0];// P(i - 1) + P(i - 2) + ... + P(i - maxPts)for(inti=1;i<=n;++i){// The prob to get point i is// P(i) = [P(i - 1) + P(i - 2) + ... + P(i - maxPts)] / maxPtsdp[i]=windowSum/maxPts;if(i<k)windowSum+=dp[i];else// The game endsans+=dp[i];if(i-maxPts>=0)windowSum-=dp[i-maxPts];}returnans;}}
classSolution:defnew21Game(self,n:int,k:int,maxPts:int)->float:# When the game ends, the point is in [k..k - 1 + maxPts]# P = 1, if n >= k - 1 + maxPts# P = 0, if n < k (note the constraints already have k <= n)ifk==0orn>=k-1+maxPts:return1.0ans=0.0dp=[1.0]+[0]*n# dp[i] := prob to have i pointswindowSum=dp[0]# P(i - 1) + P(i - 2) + ... + P(i - maxPts)foriinrange(1,n+1):# The prob to get point i is# P(i) = [P(i - 1) + P(i - 2) + ... + P(i - maxPts)] / maxPtsdp[i]=windowSum/maxPtsifi<k:windowSum+=dp[i]else:# The game endsans+=dp[i]ifi-maxPts>=0:windowSum-=dp[i-maxPts]returnans