"Leetcode" Guess number higher or Lower II

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.