Skip to content

Commit d5936c8

Browse files
authored
Create Guess_Number_Game_II.java
1 parent 48c6d48 commit d5936c8

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

arrays/Guess_Number_Game_II.java

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/*
2+
3+
Guess Number Game II
4+
5+
6+
7+
We are playing the Guess Game. The game is as follows:
8+
I pick a number from 1 to n. You have to guess which number I picked.
9+
Every time you guess wrong, I'll tell you whether the number I picked is higher or lower.
10+
However, when you guess a particular number x, and you guess wrong, you pay $x. You win the game when you guess the number I picked.
11+
12+
13+
Example
14+
15+
Given n = 10, I pick 8.
16+
First round: You guess 5, I tell you that it's higher. You pay $5.
17+
Second round: You guess 7, I tell you that it's higher. You pay $7.
18+
Third round: You guess 9, I tell you that it's lower. You pay $9.
19+
20+
Game over. 8 is the number I picked.
21+
You end up paying $5 + $7 + $9 = $21.
22+
23+
Given a particular n ≥ 1, find out how much money you need to have to guarantee a win.
24+
So when n = `10, return16`
25+
26+
27+
28+
解:
29+
Dynanmic Programming
30+
31+
递推公式:
32+
dp[i][j]表示从i到j中猜中任意数字的最小开销。
33+
假设猜数字k,i<k<j,那么需要在i到k-1和k+1到j中继续猜。
34+
依据minimax原理,对方可选择让我方开销最大的回答方式,故选择i到k-1和k+1到j中开销大的那个。
35+
故猜k时的最小开销是:
36+
k + max(dp[i][k-1], dp[k+1][j])
37+
38+
k可以取i到j,我方应当选择让自己开销最小的一个,故:
39+
dp[i][j] = min(k + max(dp[i][k-1], dp[k+1][j]),i<k<j)
40+
41+
42+
初始条件:
43+
由于每次需要用到i和j之间长度小于当前长度的dp值,所以应当按照长度递增来进行计算。
44+
当i和j相等时,长度为1,猜中的开销为0。
45+
故dp[i][i]=0。
46+
47+
*/
48+
49+
public class Solution {
50+
/**
51+
* @param n an integer
52+
* @return how much money you need to have to guarantee a win
53+
*/
54+
public int getMoneyAmount(int n) {
55+
int[][] dp = new int[n + 1][n + 1];
56+
57+
for (int len = 2; len <= n; len++) {
58+
for (int i = 1; i <= n - len + 1; i++) {
59+
int min = Integer.MAX_VALUE;
60+
min = i + dp[i + 1][i + len - 1];
61+
min = Math.min(min, i + len - 1 + dp[i][i + len - 2]);
62+
63+
for (int j = i + 1; j < i + len - 1; j++) {
64+
min = Math.min(min, j + Math.max(dp[i][j - 1], dp[j + 1][i + len - 1]));
65+
}
66+
67+
dp[i][i + len - 1] = min;
68+
}
69+
}
70+
71+
return dp[1][n];
72+
}
73+
}

0 commit comments

Comments
 (0)