Skip to content
Problem 375 · LeetCode 375(opens in a new tab)

Guess Number Higher or Lower II

MediumDynamic programming

A secret number has been picked from 1 to n. You guess a number. If you are right, the game ends. If you are wrong, you pay as many dollars as the number you guessed, and you are told whether the secret is higher or lower. Then you guess again.

Return the smallest amount of money that lets you win no matter which number was picked, if you play the best strategy.

Example 1

Input:  n = 4
Output: 4
Why:    guess 3; if lower, guess 1 (paid 3 + 1); if higher, it is 4
2 more examples and the constraints

Example 2

Input:  n = 1
Output: 0
Why:    the only number is 1, so the first guess is right

Example 3

Input:  n = 3
Output: 2
Why:    guess 2; a wrong guess costs 2 and leaves one number

Constraints

  • 1 ≤ n ≤ 200

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Recursion with a memoO(n³)
  2. Bottom-up tableO(n³)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 200Verdict
Recursion with a memoO(n³)
Passes; easiest to explain
Bottom-up tableO(n³)
Best; no recursion

n = the largest number that can be picked. Plain recursion without a memo is exponential and is left out.

Edge cases to test

  • n = 1. Your first guess is right, so you need 0.
  • n = 2. Guess 1. If wrong, it is 2, so you need 1.
  • Out-of-range sides. Guessing lo leaves lo..lo − 1, an empty range. Size the table n + 2 so dp[k + 1][hi] at k = n is still in bounds.
  • The largest n. n = 200 needs 952. The O(n³) loop is about 1.3 million steps.

Common mistakes

  • Using binary search, which minimises the number of guesses, not the money.
  • Taking the minimum of the two sides instead of the maximum: the secret is picked to hurt you.
  • Filling the table row by row from the top, so a cell reads ranges not filled yet.

How to talk through it

  1. 1Clarify. Do I pay only for wrong guesses? Is it the worst case over all secrets, not the average?
  2. 2Show binary search fails. For n = 4 it needs 5; guessing 3 first needs 4. The cost is the number, not the count.
  3. 3Define the state. cost(lo, hi): try every guess k, pay k plus the worse side, keep the best.
  4. 4Code it bottom-up. Fill by range length so every smaller range is ready. Say why the table is n + 2 wide.
  5. 5Test out loud. Run n = 1, 2, 3 and 4 by hand before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?