MediumNo. 0375

Guess Number Higher or Lower II — LeetCode 375 Python Solution

Topics
Math, Dynamic Programming, Game Theory
Reading time
3 min

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

PythonSolution
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

Related problems
No.ProblemDifficulty
0374Guess Number Higher or LowerEasy
0464Can I WinMedium
0486Predict the WinnerMedium
0877Stone GameMedium
0913Cat and MouseHard
1025Divisor GameEasy

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.