AlgoMaster Logo

New 21 Game

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Approach

In this initial approach, we simulate every possible game outcome up to the maximum point. The idea is to use recursion to try every possible draw of cards and compute the probability of reaching the target score.

Intuition:

  • We simulate each turn by drawing a card from 1 to K.
  • Recursively calculate the probabilities of reaching a score greater than or equal to N.
  • This recursion depth can get very large and become inefficient for larger values of N and K.

Code:

2. Dynamic Programming Approach

To improve efficiency, we switch to a Dynamic Programming technique, utilizing a DP array to store probabilities.

Intuition:

  • Define dp[x] as the probability of getting exactly x points.
  • Iteratively calculate probabilities for each score from 0 up to K.
  • For scores greater than K, if the score is within the range [K, N], then it contributes to the total probability outcome.

Code:

3. Optimized DP Approach

The optimized DP approach reduces space usage by using a sliding window over the DP array, effectively reducing it from O(N) to O(maxPts).

Intuition:

  • Instead of maintaining a whole DP array, keep a rolling sum of probabilities that will be averaged out.
  • This rolling window approach ensures that we only maintain necessary elements from the DP array within the range [i-maxPts, i].

Code: