Leetcode 375. Guess Number Higher or Lower II
We are playing the Guessing Game. The game is as follows:
The solution should calculate the minimum amount of money required to guarantee a win if you guess the numbers strategically.
Example:
Input: n = 10
Output: 16
Explanation: The strategy might be to go with number 7 first:
* If you guess 7, and it is wrong, there are two scenarios:
- Number is greater (possible numbers: 8, 9, 10). From here, the worst case would require 8 units to guarantee a win.
- Number is lesser (possible numbers: 1, 2, 3, 4, 5, 6). From here, the worst case would require 10 units to guarantee a win.
* Choosing 7 first will ensure the minimum cost in the worst-case scenario.
To solve this problem, we will use a dynamic programming approach. The idea is to minimize the cost for each range [i, j]
in a systematic manner.
dp[i][j]
as the minimum amount of money required to guarantee a win for the range [i, j]
.dp[i][i] = 0
because if there’s only one number, we pick it, and the cost is $0.[i, j]
, consider each number k
in that range.
k
is k + max(dp[i][k-1], dp[k+1][j])
(since it covers the worst-case scenario).k
in [i, j]
and choose the k
which minimizes this cost.#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
class Solution {
public:
int getMoneyAmount(int n) {
// Create a 2D DP array initialized to 0
vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));
// Only consider ranges of length greater than 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] = INT_MAX;
// Consider every number k in the range [i, j] as the initial guess
for (int k = i; k < j; ++k) {
// Calculate the worst cost if we pick k as the guess stop point
int cost = k + max(dp[i][k - 1], dp[k + 1][j]);
dp[i][j] = min(dp[i][j], cost);
}
}
}
return dp[1][n];
}
};
The time complexity of this algorithm is (O(n^3)) due to the three nested loops:
The space complexity is (O(n^2)) for storing the results in the dynamic programming table dp
.
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?