375. Guess Number Higher or Lower II

Posted ruruozhenhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了375. Guess Number Higher or Lower II相关的知识,希望对你有一定的参考价值。

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.

 

Approach #1: DP. [C++]

class Solution {
public:
    int getMoneyAmount(int n) {
        vector<vector<int>> dp(n+1, vector<int>(n+1, 0));
        return getMoneyAmount(dp, 1, n);
    }
    
private:
    int getMoneyAmount(vector<vector<int>>& dp, int s, int e) {
        if (s >= e) return 0;
        if (dp[s][e] != 0) return dp[s][e];
        
        int res = INT_MAX;
        for (int i = s; i <= e; ++i) {
            int tmp = i + max(getMoneyAmount(dp, s, i-1), getMoneyAmount(dp, i+1, e));
            res = min(res, tmp);
        }
        
        dp[s][e] = res;
        
        return res;
    }
};

 

Analysis:

dp[i][j] : the index from i to j how much money you have to pay.

res = i + max(fuc(), fuc());

the reasion why we use max instead of min is that we want to find the minimum money which we have to pay. If we use min in this place it will return 0 alway.

 

Approach #2: bottom to up. [C++]

    int getMoneyAmount(int n) {
        vector<vector<int>> dp(n+1, vector<int>(n+1, 0));
        for (int i = 2; i <= n; ++i) {
            for (int j = i-1; j > 0; --j) {
                int globalMin = INT_MAX;
                for (int k = j+1; k < i; ++k) {
                    int localMin = k + max(dp[j][k-1], dp[k+1][i]);
                    globalMin = min(globalMin, localMin);
                }
                dp[j][i] = j+1 == i ? j : globalMin;
            }
        }
        return dp[1][n];
    }

  

Analysis:

If j+1 == i, dp[j][i] represent two adjacent numbers, so we return the little one as the value of dp[j][i]. why not is the bigger one? I think it is realted to we solve this problem using bottom to up method. so we should get the little one‘s value firstly.

 

以上是关于375. Guess Number Higher or Lower II的主要内容,如果未能解决你的问题,请参考以下文章

375. Guess Number Higher or Lower II

375. Guess Number Higher or Lower II

375. Guess Number Higher or Lower II

leetcode375 Guess Number Higher or Lower II

LC 375. Guess Number Higher or Lower II

375 Guess Number Higher or Lower II 猜数字大小 II