Topic Links:
Topic:
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to N. You had to guess which number I picked.
Every time you guess wrong, I'll tell you whether the number I picked is higher or lower.
However, when you guess a particular number x, and your guess wrong, you pay $x. You win the game when you guess the number I picked.
Example:
n = ten, I pick 8.
First round:you guess 5, I tell you it ' s higher. You pay 5.S eCoNd RouNd :Y oug uess7,I TeLLy ouThaTI t- shIg heR.Y ouPay 7.
Third Round:you Guess 9, I tell you it's lower. You pay $9.
Game over. 8 is the number I picked.
You end up paying 5+ 7 + 9= 21st.
Given a particular n≥1, find out what much money you need to has to guarantee a win.
Ideas:
The key is to convert it to DP problem, O (n^3) solution I can't think of. /(ㄒoㄒ)/~~
Set DP[I][J] for I~j to guarantee the most cost of winning. Assuming k value, if not, then the problem is converted to guess 1~k-1,k+1~n two sub-problem, and guess K results will tell us which sub-problem to guess, so guess K to ensure that win up to Money=k+max{dp[i][k-1],dp[k+1,j]}, then in i~ The existence of a strategy in the J range is optimal, which is to guess the minimum amount of money a K needs, for Min{money} K belongs to [I,j].
Reference: Https://discuss.leetcode.com/topic/51358/java-dp-solution
Algorithm:
Public int Getmoneyamount(intN) {int[] DP =New int[n +1][n +1]; for(intK =1; K < n; k++) { for(ints =1; S + k <= N; s++) {dp[s][s + K] = Integer.max_value; for(inti = s; I < S + k; s++) {dp[s][s + K] = Math.min (Dp[s][s + K], I + Math.max (Dp[s][i-1], Dp[i +1][s + K])); } } }returndp[1][n]; }
"Leetcode" Guess number higher or Lower II