We are playing the Guessing Game. The game will work as follows:
1
and n
.x
, you will pay x
dollars. If you run out of money, you lose the game.Given a particular n
, return the minimum amount of money you need to guarantee a win regardless of what number I pick.
For example: Input: n = 10 Output: 16
Explanation: The winning strategy is as follows:
def getMoneyAmount(n):
dp = [[0] * (n + 1) for _ in range(n + 1)]
for length in range(2, n + 1):
for start in range(1, n - length + 2):
end = start + length - 1
dp[start][end] = float('inf')
for pivot in range(start, end):
cost = pivot + max(dp[start][pivot - 1], dp[pivot + 1][end])
dp[start][end] = min(dp[start][end], cost)
return dp[1][n]
# Example usage:
n = 10
result = getMoneyAmount(n)
print(f"Minimum amount needed for n = {n}: {result}") # Output: 16
n = 1
result = getMoneyAmount(n)
print(f"Minimum amount needed for n = {n}: {result}") # Output: 0
n = 2
result = getMoneyAmount(n)
print(f"Minimum amount needed for n = {n}: {result}") # Output: 1
This problem can be solved using dynamic programming. The core idea is to consider every number i
in the range [1, n]
as a potential guess. For each guess, we need to consider the worst-case scenario, i.e., whether the number is lower or higher than our guess.
Naive Approach (Brute Force - Not practical):
[1, n]
. For each guess, recursively calculate the cost for the lower and higher ranges. Choose the guess that minimizes the maximum cost of the two ranges.n
.Optimal Solution (Dynamic Programming):
dp[i][j]
represents the minimum amount of money needed to guarantee a win within the range [i, j]
.i >= j
, where dp[i][j] = 0
because no guess is needed.[i, j]
, iterate through every possible guess pivot
from i
to j
.pivot
as pivot + max(dp[i][pivot-1], dp[pivot+1][j])
. The max
function is used because we want to consider the worst-case scenario whether the number is lower or higher than pivot
.dp[i][j]
will be the minimum cost among all possible pivot
values.The dynamic programming solution has a time complexity of O(n^3)
. This is because we have a nested loop to fill the DP table. The outer loops iterate through all possible lengths and start positions, which take O(n^2)
time. The inner loop iterates through all possible pivot values within each range, which takes O(n)
time. Therefore, the total time complexity is O(n^2 * n) = O(n^3)
.
The space complexity of the dynamic programming solution is O(n^2)
because we use a 2D DP table of size (n+1) x (n+1)
to store the minimum costs for all possible ranges. This table is necessary to memoize the results of subproblems and avoid redundant calculations.
n
by breaking the problem into smaller subproblems and storing the results in the DP table.Handling the edge cases and using dynamic programming ensures that the solution is both correct and efficient for all possible values of n
within the given constraints.