Guess Number Higher or Lower II — LeetCode 375 Python Solution

MediumMathDynamic ProgrammingGame Theory
Problem
#375
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

Python
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

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

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

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.

Get Stealth Interview