aboutsummaryrefslogtreecommitdiff
path: root/new_21_game.c
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /new_21_game.c
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'new_21_game.c')
-rw-r--r--new_21_game.c38
1 files changed, 38 insertions, 0 deletions
diff --git a/new_21_game.c b/new_21_game.c
new file mode 100644
index 0000000..4076f33
--- /dev/null
+++ b/new_21_game.c
@@ -0,0 +1,38 @@
+// 837. New 21 Game
+#include <stdio.h>
+#include <stdlib.h>
+
+/*
+ * 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.
+ * during each draw, she gains an integer number of points randomly from range
+ * '[1, max_pts]', where 'max_pts' is an integer. each draw is independent and
+ * the outcomes have equal posibilities. alice stops drawing numbers when she
+ * gets 'k' or more points. return the probability that alice has 'n' or fewer
+ * points. answers within 10^-5 of the actual answer are considered accepted
+ */
+
+double new21Game(int n, int k, int max_pts) {
+ if (!k || n >= k + max_pts)
+ return 1.0;
+ double *dp = malloc((n + 1) * sizeof(double));
+ dp[0] = 1.0;
+ double sum = 1.0, ans = 0.0;
+ for (int i = 1; i <= n; ++i) {
+ dp[i] = sum / max_pts;
+ if (i < k)
+ sum += dp[i];
+ else
+ ans += dp[i];
+ if (i - max_pts >= 0)
+ sum -= dp[i - max_pts];
+ }
+ return ans;
+}
+
+int main() {
+ // new21Game(21,17,10);
+ printf("%f\n", new21Game(10, 1, 10)); // expect: 1.00000
+ printf("%f\n", new21Game(6, 1, 10)); // expect: 0.60000
+ printf("%f\n", new21Game(21, 17, 10)); // expect: 0.73278
+}