| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.New21Game; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class New21GameDynamicProgrammingSlidingWindow : INew21Game |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="n"></param> |
| | 22 | | /// <param name="k"></param> |
| | 23 | | /// <param name="maxPts"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public double New21Game(int n, int k, int maxPts) |
| 3 | 26 | | { |
| 3 | 27 | | if (k == 0 || n >= k - 1 + maxPts) |
| 1 | 28 | | { |
| 1 | 29 | | return 1; |
| | 30 | | } |
| | 31 | |
|
| 2 | 32 | | var dp = new double[n + 1]; |
| | 33 | |
|
| 2 | 34 | | dp[0] = 1.0; |
| | 35 | |
|
| 2 | 36 | | var windowSum = 0.0; |
| 2 | 37 | | var result = 0.0; |
| | 38 | |
|
| 58 | 39 | | for (var score = 1; score <= n; score++) |
| 27 | 40 | | { |
| 27 | 41 | | if (score - 1 < k) |
| 18 | 42 | | { |
| 18 | 43 | | windowSum += dp[score - 1]; |
| 18 | 44 | | } |
| | 45 | |
|
| 27 | 46 | | var outgoing = score - 1 - maxPts; |
| | 47 | |
|
| 27 | 48 | | if (outgoing >= 0 && outgoing < k) |
| 11 | 49 | | { |
| 11 | 50 | | windowSum -= dp[outgoing]; |
| 11 | 51 | | } |
| | 52 | |
|
| 27 | 53 | | dp[score] = windowSum / maxPts; |
| | 54 | |
|
| 27 | 55 | | if (score >= k) |
| 11 | 56 | | { |
| 11 | 57 | | result += dp[score]; |
| 11 | 58 | | } |
| 27 | 59 | | } |
| | 60 | |
|
| 2 | 61 | | return result; |
| 3 | 62 | | } |
| | 63 | | } |