Leetcode 837: New 21 Game

grid47
grid47
Exploring patterns and algorithms
Aug 15, 2024 7 min read

Alice is playing a game where she starts with 0 points and randomly draws a number from the range [1, maxPts] each time. Alice continues drawing until her points reach or exceed a target value k. After each draw, she may stop if her total points reach or exceed k. The goal is to determine the probability that Alice has at most n points before reaching k points.
Problem
Approach
Steps
Complexity
Input: The input consists of three integers: n, k, and maxPts. Here, n is the maximum number of points Alice can have without exceeding it, k is the target score Alice needs to reach or exceed to stop drawing, and maxPts is the maximum number of points Alice can draw in each round.
Example: Input: n = 15, k = 10, maxPts = 5
Constraints:
• 0 <= k <= n <= 10^4
• 1 <= maxPts <= 10^4
Output: Return the probability that Alice has at most n points when she stops drawing.
Example: Output: 0.80000
Constraints:
• The probability should be accurate within a relative or absolute error of 10^-5.
Goal: To calculate the probability that Alice's points are at most n before she reaches the target k.
Steps:
• Step 1: Initialize a dp array to store the probabilities of Alice having exactly i points.
• Step 2: Start with the base case where Alice has 0 points (probability = 1).
• Step 3: For each possible score from 1 to n, calculate the probability of reaching that score by drawing a number from the range [1, maxPts].
• Step 4: Use a sliding window to sum the probabilities efficiently to calculate the next values in the dp array.
• Step 5: If the points exceed or reach k, stop the process and sum the probabilities for the cases where the points are less than or equal to n.
Goal: The values of n, k, and maxPts must satisfy the given constraints.
Steps:
• n, k, and maxPts should be valid as per the input ranges.
Assumptions:
• Alice draws random numbers independently and each draw has an equal probability of any number in the range [1, maxPts].
Input: Input: n = 15, k = 10, maxPts = 5
Explanation: In this case, Alice can draw numbers from 1 to 5, and she needs to stop when her points exceed or equal 10. We need to calculate the probability that she has 15 or fewer points before stopping.

Input: Input: n = 10, k = 1, maxPts = 10
Explanation: Alice draws a single card and immediately stops when she reaches or exceeds the target k = 1. Therefore, the probability of having 10 or fewer points is 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus