Coins in a 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?
Given values array A = [1,2,2], return true.
Given A = [1,2,4], return false.
思路: 因为硬币的总价值为固定的,要想让先手获得的价值更多即意味着先手取完之后留给后手的价值是该条件下最少的(如何坑对方)。DP[i] 表示先手在还剩n枚硬币的条件下,能获得最多的价值。sum[i] 表示枚硬币的总价值。DP[i] = sum[i] - min(DP[i - 1], DP[i - 2])。
1 public class Solution { 2 /** 3 * @param values: an array of integers 4 * @return: a boolean which equals to true if the first player will win 5 */ 6 //dp[n] 表示还剩n枚硬币时,先手能获得的最大值。 7 public boolean firstWillWin(int[] values) { 8 if (values == null || values.length == 0) { 9 return true; 10 } 11 if (values.length <= 2) { 12 return true; 13 } 14 int sum = 0; 15 for (int i : values) { 16 sum += i; 17 } 18 int[] dp = new int[values.length + 1]; 19 int n = values.length; 20 dp[1] = values[n - 1]; 21 dp[2] = dp[1] + values[n - 2]; 22 int curSum = dp[2]; 23 for (int i = 3; i <= n; i++) { 24 curSum += values[n - i]; 25 int min = Math.min(dp[i - 1], dp[i - 2]); 26 dp[i] = curSum - min; 27 } 28 return dp[n] > sum / 2; 29 } 30 }

浙公网安备 33010602011771号