Programming & Development / April 10, 2025

LeetCode 375: Guess Number Higher or Lower II – Dynamic Programming Solution

LeetCode 375 Guess Number Higher or Lower II dynamic programming optimal strategy game theory Python minimum cost

πŸ“˜ Problem Statement

We are playing a guessing game. The game follows these rules:

  • I pick a number between 1 and n. You have to guess which number I picked.
  • Every time you guess a number, I’ll tell you whether it’s too high, too low, or correct.
  • However, you have to minimize your maximum cost in the worst-case scenario, where the cost is defined as the number of guesses you make.

You need to implement a function that returns the minimum amount of money you have to spend to guess the number optimally. The minimum cost is defined as the worst-case cost of the optimal guessing strategy.

🧠 Key Insight

This problem involves dynamic programming because we want to compute the minimum cost for a range of possible guesses using previously computed results for smaller ranges.

To solve the problem, we must minimize the worst-case number of guesses required when guessing a number from a given range. For each guess, we can split the range into two subproblems:

  1. The numbers lower than the guess.
  2. The numbers higher than the guess.

By recursively solving these subproblems and using dynamic programming to store intermediate results, we can compute the optimal solution.

Steps:

  1. Recursive Problem Definition: For a range [low, high], the optimal cost is the minimum of the costs for all possible guesses x within this range. For each guess x, the cost will be the maximum between the cost of guessing numbers lower than x and higher than x, plus the cost of the guess x itself (which is x).
  2. Dynamic Programming (Memoization): Store results for each subproblem (range [low, high]) to avoid redundant calculations.

πŸ’‘ Approach

  1. Define the DP Function: Let dp(low, high) be the minimum cost to guess a number between low and high.
  2. Base Case: If low >= high, there is no need to guess, so dp(low, high) = 0.
  3. Recursive Case: For each x in the range [low, high], compute the cost as max(dp(low, x-1), dp(x+1, high)) + x, and minimize this cost across all x.

🐍 Python Code

python

class Solution:
    def getMoneyAmount(self, n: int) -> int:
        # Memoization table to store the results of subproblems
        dp = [[0] * (n + 1) for _ in range(n + 1)]
        
        # Fill the DP table for ranges from 2 to n
        for length in range(2, n + 1):  # Length of the range
            for low in range(1, n - length + 2):  # Start of the range
                high = low + length - 1  # End of the range
                # Initialize dp[low][high] with a large value
                dp[low][high] = float('inf')
                # Try every possible guess within the range
                for guess in range(low, high):
                    # The cost is the guess + the worst of the two remaining ranges
                    dp[low][high] = min(dp[low][high], guess + max(dp[low][guess - 1], dp[guess + 1][high]))
        
        # The final result for the range [1, n] is stored in dp[1][n]
        return dp[1][n]

πŸ” Step-by-Step Explanation

1. Memoization Table Initialization

python

dp = [[0] * (n + 1) for _ in range(n + 1)]
  • We create a 2D memoization table dp where dp[i][j] stores the minimum cost to guess a number between i and j.
  • Initially, all values are set to 0.

2. Filling the DP Table

python

for length in range(2, n + 1):  # Length of the range
    for low in range(1, n - length + 2):  # Start of the range
        high = low + length - 1  # End of the range
  • We iterate through all possible subranges [low, high] of lengths from 2 to n. For each subrange, we compute the minimum cost to guess a number optimally.

3. Try Every Possible Guess

python

for guess in range(low, high):
    dp[low][high] = min(dp[low][high], guess + max(dp[low][guess - 1], dp[guess + 1][high]))
  • For each possible guess x in the range [low, high], we calculate the cost of guessing x as x + max(dp[low, x-1], dp[x+1, high]), where:
  • dp[low, x-1] is the cost of guessing in the lower part of the range.
  • dp[x+1, high] is the cost of guessing in the higher part of the range.
  • We take the minimum of these costs across all possible guesses.

4. Return the Result

python

return dp[1][n]
  • After filling the DP table, the result for the range [1, n] is stored in dp[1][n], which we return.

πŸ’‘ Example

python

Input:
n = 10

Output:
16

Explanation:
The optimal strategy is to guess the number 4 first, which will lead to a worst-case cost of 16 for the range [1, 10].

⏱️ Time & Space Complexity

MetricComplexityTime ComplexityO(n^3)Space ComplexityO(n^2)

  • Time Complexity: The outer loop iterates over all possible subranges [low, high], and for each subrange, we try each possible guess. This results in a time complexity of O(n^3).
  • Space Complexity: We use a 2D table dp to store the results for each subrange, so the space complexity is O(n^2).

🧡 Final Thoughts

This problem is a classic example of dynamic programming and game theory. By breaking down the problem into subproblems and solving them efficiently using memoization, we can determine the minimum cost of guessing the number in the worst-case scenario.

  • Dynamic Programming: The DP approach helps us store intermediate results, avoiding redundant calculations and ensuring an optimal solution.
  • Minimizing Worst-Case Cost: The problem focuses on minimizing the cost of the worst-case scenario, which is key in game theory problems where decisions must be made based on potential outcomes.

This solution provides an optimal and efficient way to approach guessing games and similar problems involving ranges and costs.


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex