Skip to content

Commit 17034a4

Browse files
committed
Add solution #837
1 parent 87bf4ab commit 17034a4

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -644,6 +644,7 @@
644644
834|[Sum of Distances in Tree](./0834-sum-of-distances-in-tree.js)|Hard|
645645
835|[Image Overlap](./0835-image-overlap.js)|Medium|
646646
836|[Rectangle Overlap](./0836-rectangle-overlap.js)|Easy|
647+
837|[New 21 Game](./0837-new-21-game.js)|Medium|
647648
841|[Keys and Rooms](./0841-keys-and-rooms.js)|Medium|
648649
844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy|
649650
846|[Hand of Straights](./0846-hand-of-straights.js)|Medium|

solutions/0837-new-21-game.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* 837. New 21 Game
3+
* https://leetcode.com/problems/new-21-game/
4+
* Difficulty: Medium
5+
*
6+
* Alice plays the following game, loosely based on the card game "21".
7+
*
8+
* Alice starts with 0 points and draws numbers while she has less than k points. During each draw,
9+
* she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an
10+
* integer. Each draw is independent and the outcomes have equal probabilities.
11+
*
12+
* Alice stops drawing numbers when she gets k or more points.
13+
*
14+
* Return the probability that Alice has n or fewer points.
15+
*
16+
* Answers within 10-5 of the actual answer are considered accepted.
17+
*/
18+
19+
/**
20+
* @param {number} n
21+
* @param {number} k
22+
* @param {number} maxPts
23+
* @return {number}
24+
*/
25+
var new21Game = function(n, k, maxPts) {
26+
if (k === 0 || n >= k + maxPts - 1) return 1.0;
27+
28+
const dp = new Array(n + 1).fill(0);
29+
dp[0] = 1.0;
30+
31+
let sum = 1.0;
32+
for (let i = 1; i <= n; i++) {
33+
dp[i] = sum / maxPts;
34+
if (i < k) {
35+
sum += dp[i];
36+
}
37+
if (i >= maxPts) {
38+
sum -= dp[i - maxPts];
39+
}
40+
}
41+
42+
let result = 0;
43+
for (let i = k; i <= n; i++) {
44+
result += dp[i];
45+
}
46+
47+
return result;
48+
};

0 commit comments

Comments
 (0)