Guess Number Higher or Lower II - Problem
You're playing a strategic guessing game where you must guarantee a win regardless of what your opponent does!
Here's how the game works:
- Your opponent picks a secret number between
1andn - You guess a number. If correct, you win! ๐
- If wrong, your opponent tells you if the secret number is higher or lower
- Each wrong guess costs you money equal to the number you guessed
- If you run out of money, you lose the game
The Challenge: Given n, determine the minimum amount of money you need to guarantee a win against the worst possible opponent (one who tries to make you spend the most money).
Example: For n = 3, if you guess 2 first and it's wrong, you pay $2. Then you know the answer (either 1 or 3) and can guess correctly. So you need at least $2 to guarantee a win.
Input & Output
example_1.py โ Small Range
$
Input:
n = 1
โบ
Output:
0
๐ก Note:
Only one number to guess (1), so we get it right immediately with no cost.
example_2.py โ Classic Case
$
Input:
n = 10
โบ
Output:
16
๐ก Note:
Optimal strategy: guess 7 first. If wrong and told 'lower', we need to search [1,6] which costs 5 more. If wrong and told 'higher', we need to search [8,10] which costs 2 more. So worst case is 7 + 5 = 12. But the actual optimal first guess yields cost 16.
example_3.py โ Edge Case
$
Input:
n = 2
โบ
Output:
1
๐ก Note:
We can guess 1 first. If wrong, we know the answer is 2. Cost is 1 in worst case. Alternatively, guess 2 first with cost 2 in worst case. So optimal is 1.
Visualization
Tap to expand
Understanding the Visualization
1
Choose Strategy
Pick a number k to guess first in range [1,n]
2
Analyze Outcomes
If wrong, opponent splits problem into [1,k-1] or [k+1,n]
3
Worst Case Cost
Opponent chooses the more expensive subproblem
4
Minimize Maximum
Choose k that minimizes the worst-case total cost
Key Takeaway
๐ฏ Key Insight: This minimax problem requires us to minimize our maximum loss by choosing optimal pivot points that balance the cost of both possible opponent responses.
Time & Space Complexity
Time Complexity
O(nยณ)
Three nested loops: O(n) range lengths ร O(n) starting positions ร O(n) pivot choices
โ Quadratic Growth
Space Complexity
O(nยฒ)
2D DP table to store results for all possible ranges [i,j]
โ Quadratic Space
Constraints
- 1 โค n โค 200
- The answer is guaranteed to fit in a 32-bit integer
- You must find the minimum cost to guarantee a win against any opponent strategy
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code