Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

837. New 21 Game

Explanation

To solve this problem, we can use dynamic programming. We will iterate backwards starting from point k, calculating the probability of having n or fewer points at each step. At each point, the probability of having n or fewer points is the sum of the probabilities of reaching n or fewer points in the next maxPts draws, divided by maxPts. We will store these probabilities in an array and return the probability at the starting point 0.

  • Time complexity: O(n * maxPts)
  • Space complexity: O(n)
class Solution {
    public double new21Game(int n, int k, int maxPts) {
        double[] dp = new double[n + maxPts + 1];
        double sum = 0;
        
        for (int i = k; i <= n && i < k + maxPts; i++) {
            dp[i] = 1.0;
            sum += dp[i];
        }
        
        for (int i = k - 1; i >= 0; i--) {
            dp[i] = sum / maxPts;
            sum += dp[i] - dp[i + maxPts];
        }
        
        return dp[0];
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.