837. New 21 Game #2064
-
Topics: Alice plays the following game, loosely based on the card game "21". Alice starts with Alice stops drawing numbers when she gets Return the probability that Alice has Answers within Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to compute the probability that Alice has Approach
Let's implement this solution in PHP: 837. New 21 Game <?php
/**
* @param Integer $n
* @param Integer $k
* @param Integer $maxPts
* @return Float
*/
function new21Game($n, $k, $maxPts) {
if ($k == 0) {
return 1.0;
}
$dp = array_fill(0, $k, 0.0);
$dp[0] = 1.0;
$windowSum = 1.0;
for ($i = 1; $i < $k; $i++) {
$dp[$i] = $windowSum * (1.0 / $maxPts);
$windowSum += $dp[$i];
if ($i >= $maxPts) {
$windowSum -= $dp[$i - $maxPts];
}
}
$totalProb = 0.0;
$maxStop = min($n, $k - 1 + $maxPts);
for ($j = 0; $j < $k; $j++) {
$lowS = max($k, $j + 1);
$highS = min($j + $maxPts, $maxStop);
if ($lowS <= $highS) {
$count = $highS - $lowS + 1;
$totalProb += $dp[$j] * $count;
}
}
$totalProb /= $maxPts;
return $totalProb;
}
// Test cases
echo number_format(new21Game(10, 1, 10), 5, '.', ''), PHP_EOL; // Output: 1.00000
echo number_format(new21Game(6, 1, 10), 5, '.', ''), PHP_EOL; // Output: 0.60000
echo number_format(new21Game(21, 17, 10), 5, '.', ''), PHP_EOL; // Output: 0.73278
?> Explanation:
This approach efficiently computes the desired probability using dynamic programming and a sliding window, ensuring optimal performance even for large inputs. |
Beta Was this translation helpful? Give feedback.
We need to compute the probability that Alice has
n
or fewer points when she stops drawing numbers in the game described. The game involves Alice starting with 0 points and drawing numbers from the range[1, maxPts]
until her total points reach or exceedk
. The solution involves dynamic programming and a sliding window technique to efficiently compute the probabilities.Approach
Problem Analysis: Alice starts at 0 points and draws numbers from 1 to
maxPts
(each with equal probability) until her total points are at leastk
. We need to find the probability that her total points when she stops aren
or fewer. The solution involves:dp[i]
r…