File tree 2 files changed +49
-0
lines changed
2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change 644
644
834|[ Sum of Distances in Tree] ( ./0834-sum-of-distances-in-tree.js ) |Hard|
645
645
835|[ Image Overlap] ( ./0835-image-overlap.js ) |Medium|
646
646
836|[ Rectangle Overlap] ( ./0836-rectangle-overlap.js ) |Easy|
647
+ 837|[ New 21 Game] ( ./0837-new-21-game.js ) |Medium|
647
648
841|[ Keys and Rooms] ( ./0841-keys-and-rooms.js ) |Medium|
648
649
844|[ Backspace String Compare] ( ./0844-backspace-string-compare.js ) |Easy|
649
650
846|[ Hand of Straights] ( ./0846-hand-of-straights.js ) |Medium|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments