MediumNo. 0375
Guess Number Higher or Lower II — LeetCode 375 Python Solution
- Pattern
- Dynamic Programming
- Topics
- Math, Dynamic Programming, Game Theory
- Reading time
- 3 min
- Source
- leetcode.com
The problem
We are playing the Guessing Game. The game will work as follows: I pick a number between 1 and n.
Example
- Input
- n = 10
- Output
- 16
- Explanation
- The winning strategy is as follows:
Python solution
class Solution:
def getMoneyAmount(self, n: int) -> int:
f = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(n - 1, 0, -1):
for j in range(i + 1, n + 1):
f[i][j] = j + f[i][j - 1]
for k in range(i, j):
f[i][j] = min(f[i][j], max(f[i][k - 1], f[k + 1][j]) + k)
return f[1][n]Complexity
- Time
- O(n·m) (typical)
- Space · auxiliary
- O(n·m)or optimized
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 375. Guess Number Higher or Lower II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0374 | Guess Number Higher or Lower | Easy |
| 0464 | Can I Win | Medium |
| 0486 | Predict the Winner | Medium |
| 0877 | Stone Game | Medium |
| 0913 | Cat and Mouse | Hard |
| 1025 | Divisor Game | Easy |
Frequently asked questions
- How hard is LeetCode 375. Guess Number Higher or Lower II?
LeetCode 375. Guess Number Higher or Lower II is rated Medium on LeetCode.
- What topics does LeetCode 375. Guess Number Higher or Lower II cover?
LeetCode 375. Guess Number Higher or Lower II is tagged Math, Dynamic Programming and Game Theory on LeetCode.