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 Higher or Lower II INPUT Numbers from 1 to n 1 2 3 n = 3 Game Rules: - Guess a number - Wrong guess costs $x - Get hint: higher/lower - Find minimum cost to guarantee a win ? ALGORITHM STEPS 1 DP Table Setup dp[i][j] = min cost for [i,j] 2 Try Each Guess For pivot k in range [i,j] 3 Minimax Strategy k + max(dp[i][k-1], dp[k+1][j]) 4 Find Minimum min over all pivots k DP Table for n=3: 1 2 3 0 1 2 Guess 2 first: Cost = $2, then know answer 2 1 3 FINAL RESULT Optimal Strategy: Always guess 2 first Guess 2 Pay $2 Lower: 1 Higher: 3 Correct: WIN! Output: 2 [OK] Minimum guaranteed Key Insight: Use Dynamic Programming with minimax strategy. For each range [i,j], try every possible guess k. The cost is k + max(left subproblem, right subproblem) because we must handle the worst case. Take the minimum over all choices of k to find the optimal first guess for that range. TutorialsPoint - Guess Number Higher or Lower II | Optimal DP Solution
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