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.
题目大意:猜给定范围的数字,猜错了需要付相应的钱,求赢得游戏所需的最少的钱。
代码
package DP; /** * @author OovEver * 2018/1/8 13:46 */ public class LeetCode3752 { public static int getMoneyAmount(int n) { // 其中dp[i][j]表示从数字i到j之间猜中任意一个数字最少需要花费的钱数 int[][] dp = new int[n + 1][n + 1]; // j代表当前的处理长度 for(int j=2;j<=n;j++) { for(int i=j-1;i>0;i--) { int globalMin = Integer.MIN_VALUE; for(int k=i+1;k<j;k++) { int localMax =k+ Math.max(dp[i][k - 1], dp[k + 1][j]); globalMin = Math.min(globalMin, localMax); } dp[i][j] = i + 1 == j ? i : globalMin; } } return dp[1][n]; } }