Guess Number Higher or Lower II - Problem

We are playing the Guessing Game. The game will work as follows:

  • I pick a number between 1 and n.
  • You guess a number.
  • If you guess the right number, you win the game.
  • If you guess the wrong number, then I will tell you whether the number I picked is higher or lower, and you will continue guessing.
  • Every time you guess a wrong number x, you will pay x dollars.
  • If you run out of money, you lose the game.

Given a particular n, return the minimum amount of money you need to guarantee a win regardless of what number I pick.

Input & Output

Example 1 — Small Range
$ Input: n = 3
Output: 2
💡 Note: Optimal strategy: guess 2 first. If wrong, pay 2 dollars. In worst case, still need to guess between [1,1] or [3,3] which costs 0 more. Total worst case: 2 + 0 = 2.
Example 2 — Minimum Case
$ Input: n = 1
Output: 0
💡 Note: Only one number to guess, so no wrong guesses possible. Cost is 0.
Example 3 — Larger Range
$ Input: n = 10
Output: 16
💡 Note: For range [1,10], optimal strategy involves guessing numbers that minimize the worst-case cost across all possible target numbers.

Constraints

  • 1 ≤ n ≤ 200

Visualization

Tap to expand
Guess Number Game: Find Minimum Guaranteed CostRange [1, n]Target number hidden hereYour Guess: kWrong guess costs k dollarsFeedbackHigher or Lower hintGame Theory StrategyFor guess k in range [i,j]: Cost = k + max(cost[i,k-1], cost[k+1,j])Choose k that minimizes this worst-case costExample: n=3Optimal: Guess 2 first → Maximum cost: 2
Understanding the Visualization
1
Game Setup
Target number chosen from range [1,n], we must guarantee a win
2
Cost Calculation
Each wrong guess costs that number, we pay for mistakes
3
Optimal Strategy
Find minimum cost to handle the worst-case scenario
Key Takeaway
🎯 Key Insight: This is a minimax problem - minimize the maximum cost by choosing optimal guessing strategies using dynamic programming
Asked in
Google 12 Microsoft 8 Amazon 6
78.2K Views
Medium Frequency
~35 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen