|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Recursive function to calculate the minimum money required to guarantee a win |
| 4 | + // for the range [start, end]. We use dynamic programming to memoize the results. |
| 5 | + int solve(int start, int end, vector<vector<int>>& dp) { |
| 6 | + // Base case: If start is greater than or equal to end, no money is needed. |
| 7 | + if (start >= end) return 0; |
| 8 | + |
| 9 | + // Check if the result is already computed (memoized). If so, return it. |
| 10 | + if (dp[start][end] != -1) return dp[start][end]; |
| 11 | + |
| 12 | + // Initialize maxi with a very large value to store the minimum amount of money. |
| 13 | + int maxi = INT_MAX; |
| 14 | + |
| 15 | + // Try every number i in the range [start, end] as a potential guess. |
| 16 | + for (int i = start; i <= end; i++) { |
| 17 | + // Calculate the cost of guessing i: |
| 18 | + // - i is the cost of guessing i. |
| 19 | + // - The two ranges are [start, i-1] and [i+1, end]. |
| 20 | + // We want to minimize the worst-case scenario, so we take the maximum |
| 21 | + // of the two subranges and add the cost of guessing i. |
| 22 | + maxi = min(maxi, i + max(solve(start, i - 1, dp), solve(i + 1, end, dp))); |
| 23 | + } |
| 24 | + |
| 25 | + // Memoize the result for this range [start, end] and return the calculated value. |
| 26 | + return dp[start][end] = maxi; |
| 27 | + } |
| 28 | + |
| 29 | + // Function to initiate the process for the full range [1, n] |
| 30 | + int getMoneyAmount(int n) { |
| 31 | + // Create a 2D DP table to store the minimum money required for each range. |
| 32 | + // Initialize all values to -1 to signify that they are not computed yet. |
| 33 | + vector<vector<int>> dp(n + 1, vector<int>(n + 1, -1)); |
| 34 | + |
| 35 | + // Start solving for the range [1, n] |
| 36 | + return solve(1, n, dp); |
| 37 | + } |
| 38 | +}; |
0 commit comments