#375
Guess Number Higher or Lower II
MediumMathDynamic ProgrammingGame TheoryDynamic ProgrammingGame Theory
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n²) |
💡
Intuition
Time O(n²)Space O(n²)
The optimal solution uses dynamic programming to minimize the maximum cost by storing results of subproblems. This avoids redundant calculations and speeds up the process significantly.
⚙️
Algorithm
3 steps- 1Step 1: Create a 2D array dp where dp[i][j] represents the minimum cost to guarantee a win between numbers i and j.
- 2Step 2: Fill the dp array for ranges of increasing lengths, calculating the cost for each possible guess in that range.
- 3Step 3: For each guess, calculate the worst-case cost and update the dp table accordingly.
solution.py12 lines
1# Full working Python code
2class Solution:
3 def getMoneyAmount(self, n: int) -> int:
4 dp = [[0] * (n + 1) for _ in range(n + 1)]
5 for length in range(2, n + 1):
6 for start in range(1, n - length + 2):
7 end = start + length - 1
8 dp[start][end] = float('inf')
9 for x in range(start, end):
10 cost = x + max(dp[start][x - 1], dp[x + 1][end])
11 dp[start][end] = min(dp[start][end], cost)
12 return dp[1][n]ℹ
Complexity note: The time complexity remains O(n²) due to the nested loops, but we now use O(n²) space to store results of subproblems, which allows us to avoid redundant calculations.
- 1Minimizing the maximum cost is crucial to guarantee a win.
- 2Dynamic programming helps break down the problem into manageable subproblems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.