There are n coins in a line. Two players take turns to take one or two coins from right side until there are no more coins left. The player who take the last coin wins.
Could you please decide the first play will win or lose?
/** * Statement: dp[i], when i coins last, if the person now taking the coin could win * Func: dp[i] = true if dp[i-1] or dp[i-2] is false * Init: dp[0] = false, dp[1] = true; * Ans: dp[n] * */publicbooleanfirstWillWin(int n) {if(n==0) returnfalse;if(n==1) returntrue;boolean[] dp =newboolean[n+1]; dp[0] =false; dp[1] =true;for(int i=2; i<=n; i++){if(dp[i-1]==false|| dp[i-2]==false) dp[i] =true; }return dp[n];}
395t Coin In Line II
There are n coins with different value in a line. Two players take turns to take one or two coins from left side until there are no more coins left. The player who take the coins with the most value wins.
Could you please decide the first player will win or lose?
/** * Statement: dp[i], when i coins last, the money the person now taking the coin more than opponent * Func: dp[i] = max(sum[i]-dp[i-1], sum[i]-dp[i-2]); * Init: postSum, 剩i張時sum[i] * Ans: dp[n] > sum/2 */publicbooleanfirstWillWin(int[] values) {int n =values.length;int[] sum =newint[n+1];int[] dp =newint[n+1];for(int i=1; i<=n; i++){ sum[i] = sum[i-1]+values[n-i]; } dp[1] = values[n-1];for(int i=2; i<=n; i++){ dp[i] =Math.max(sum[i]-dp[i-1], sum[i]-dp[i-2]); }return dp[n] > sum[n]/2;}
486. Predict the Winner(由下往上更新)
An array of numbers, 2 players take pile from each side by turns. Return if player 1 can win
State: dp[i][j] = pick from nums[i] to nums[j], the number you has more than competitor