Guess Number Higher or Lower II

来源:互联网 发布:娱乐圈明星爆料知乎 编辑:程序博客网 时间:2024/05/20 14:25

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 that it's higher. You pay $5.Second round: You guess 7, I tell you that it's higher. You pay $7.Third round:  You guess 9, I tell you that 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.

Hint:

  1. The best strategy to play the game is to minimize the maximum loss you could possibly face. Another strategy is to minimize the expected loss. Here, we are interested in thefirst scenario.
  2. Take a small example (n = 3). What do you end up paying in the worst case?
  3. Check out this article if you're still stuck.
  4. The purely recursive implementation of minimax would be worthless for even a small n. You MUST use dynamic programming.
  5. As a follow-up, how would you modify your code to solve the problem of minimizing the expected loss, instead of the worst-case loss?
思路:

要我们在最坏情况下我们支付最少的钱。也就是说要考虑所有y的情况。

我们假定选择了一个错误的数x,(1<=x<=n && x!=y )那么就知道接下来应该从[1,x-1 ] 或者[x+1,n]中进行查找。 假如我们已经解决了[1,x-1] 和 [x+1,n]计算问题,我们将其表示为solve(L,x-1) 和solve(x+1,n),那么我们应该选择max(solve(L,x-1),solve(x+1,n)) 这样就是求最坏情况下的损失。总的损失就是 f(x) = x + max(solve(L,x-1),solve(x+1,n))

那么将x从1~n进行遍历,取使得 f(x) 达到最小,来确定最坏情况下最小的损失,也就是我们初始应该选择哪个数。

public class Solution {    public int getMoneyAmount(int n) {        if(n<0) return 0;        int[][] dp = new int[n+1][n+1];        return calculate(dp, 1, n);    }        public int calculate(int[][] dp, int L, int R){        if(L>=R) return 0;        if(dp[L][R]!=0) return dp[L][R];        dp[L][R] = Integer.MAX_VALUE;        for(int i=L; i<=R; i++){            dp[L][R] = Math.min(dp[L][R], i+Math.max(calculate(dp,L,i-1), calculate(dp, i+1, R)));        }        return dp[L][R];    }}
0 0
原创粉丝点击