Leetcode 375. Guess Number Higher or Lower II
We are playing the Guessing Game. The game works as follows:
1
and n
.x
, and you guess wrong, you pay x
dollars.Given a particular n
, return the minimum amount of money you need to guarantee a win, regardless of which number I pick.
What is the range of n
?
Let’s assume 1 ≤ n ≤ 200
.
Is this a dynamic programming problem?
Yes, this problem can be approached using dynamic programming.
Do we consider the cost of correct guesses?
No, only the cost of incorrect guesses is considered.
Are the guesses sequential or can they be in any order?
The guesses can be in any order, but we need to find a strategy that minimizes the total cost.
dp[i][j]
as the minimum cost required to guess the right number in the range [i, j]
.i == j
, dp[i][j] = 0
, because no cost is incurred if the range has only one number.i > j
, dp[i][j] = 0
, because it’s an invalid range.k
in the range [i, j]
, the cost we pay is k + max(dp[i][k-1], dp[k+1][j])
. This is because if we guess k
, the cost is k
. If the actual number is lower we need to pay dp[i][k-1]
, if it’s higher we pay dp[k+1][j]
.public class Solution {
public int getMoneyAmount(int n) {
int[][] dp = new int[n + 1][n + 1];
for (int length = 2; length <= n; length++) {
for (int i = 1; i <= n - length + 1; i++) {
int j = i + length - 1;
dp[i][j] = Integer.MAX_VALUE;
for (int k = i; k < j; k++) {
int cost = k + Math.max(dp[i][k - 1], dp[k + 1][j]);
dp[i][j] = Math.min(dp[i][j], cost);
}
}
}
return dp[1][n];
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.getMoneyAmount(10)); // Example test case
}
}
The time complexity of this approach is (O(n^3)) due to the three nested loops:
i
of the range.k
within the range [i, j]
.Since we are considering all subranges and possible guesses for these subranges, the cubic complexity is justified. This is acceptable given the constraint ( n \leq 200 ).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?