New 21 Game — LeetCode 837 Python Solution
MediumMathDynamic ProgrammingSliding WindowProbability and Statistics
- Problem
- #837
- Pattern
- Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Alice plays the following game, loosely based on the card game "21". Alice starts with 0 points and draws numbers while she has less than k points.
Example
- Input
- n = 10, k = 1, maxPts = 10
- Output
- 1.00000
- Explanation
- Alice gets a single card, then stops.
Python solution
Python
class Solution:
def new21Game(self, n: int, k: int, maxPts: int) -> float:
@cache
def dfs(i: int) -> float:
if i >= k:
return int(i <= n)
if i == k - 1:
return min(n - k + 1, maxPts) / maxPts
return dfs(i + 1) + (dfs(i + 1) - dfs(i + maxPts + 1)) / maxPts
return dfs(0)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) to O(n) auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 837. New 21 Game is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
LeetCode 2110Number of Smooth Descent Periods of a StockMediumLeetCode 470Implement Rand10() Using Rand7()MediumLeetCode 1040Moving Stones Until Consecutive IIMediumLeetCode 1093Statistics from a Large SampleMediumLeetCode 1610Maximum Number of Visible PointsHardLeetCode 2269Find the K-Beauty of a NumberEasy
Frequently asked questions
- How hard is LeetCode 837. New 21 Game?
- LeetCode 837. New 21 Game is rated Medium on LeetCode.
- What topics does LeetCode 837. New 21 Game cover?
- LeetCode 837. New 21 Game is tagged Math, Dynamic Programming, Sliding Window and Probability and Statistics on LeetCode.