原题:
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have 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 you guess wrong, you pay $x. You win the game when you guess the number I picked.
Example:
n = 10, I pick 8.
First round: You guess 5,I tell you it’s higher.You pay $5.
Second round:You guess 7, I tell you it’s higher.You pay $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 = $21
Given a particular n ≥ 1, find out how much money you need to have to guarantee a win.
分析:题意为猜数字,要求在猜中1到n中选定好的某个数,猜错会话费相应的钱数。
很容易想到为了保证能猜出数字,所以按照最坏的情况来计算,因此想到二分查找。但是此题的解题思路却不是这样。下面举例来说明:
若n=3,第一步肯定先猜中间的数2,因为若不是2,根据提示就可以正确猜出数字,这种情况代价为2
若n=4,按照二分查找,第一步先猜2,若大了,则正确数字肯定为1,代价为2
,若低了,选定的数字在3和4中,则下一步猜较小的数3,这样代价最小,最坏情况下总代价为2+3=5.
若第一步先猜3,大了则数字为小了的情况下下一步猜1,总代价为1+3=4<5
若n=5,按照二分查找,代价为3+4=7。正确情况是2+4=6<7.
此题是最小化最大值问题,要求用动态规划的算法解题。设置二维数组dp[i][j]表示在数字i到j之间猜中任意
一个数字最少需要花费的代价。在区间i-j内的每个数字进行遍历,计算其代价保存到local_max变量中,计算出每个数字对应的local_max,得到这些local_max的最大值global_min即i到j之间猜中任意一个数字最少需要花费的代价。假设在i和j之间某个数字K,其local_max=k+Math.max(dp[j][k-1], dp[k+1][i]),表示代价为k左边区间的最大代价加上自己本身再加上右边区间的最大代价。最后判断i和j是否相邻,若相邻则代价为i(较小者)。
得到了i到j的dp[i][j],最后得到dp[1][n]即为所求
Java实现如下:
public class Solution {
public int getMoneyAmount(int n) {
int[][] dp = new int[n+1][n+1];
for (int i = 1; i <= n; i++) {
for (int j = i-1; j >0; j--) {
int global_min = Integer.MAX_VALUE;
for (int k = j+1; k < i; k++) {
int local_max = k+Math.max(dp[j][k-1], dp[k+1][i]);
global_min = Math.min(local_max, global_min);
}
dp[j][i] = j+1==i?j:global_min;
}
}
return dp[1][n];
}
}