Coins In A Line II
2018-04-05 本文已影响0人
Star_C
Question
A follow-up from previous question
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.
Example
Given values array A = [1,2,2], return true.
Given A = [1,2,4], return false.
Idea
Don't think it too complicated. You do not have to change the dp function. Just keep track of the maximum amount which the first player can take, and check if it exceeds half of the total amount.
public class Solution {
/**
* @param values: a vector of integers
* @return: a boolean which equals to true if the first player will win
*/
public boolean firstWillWin(int[] values) {
int n = values.length;
if (n == 0) return false;
if (n == 1 || n == 2) return true;
boolean[] canFisrtPlayerTake = new boolean[n + 1];
int firstTotal = 0;
int sum = 0;
canFisrtPlayerTake[0] = false;
canFisrtPlayerTake[1] = true;
canFisrtPlayerTake[2] = true;
sum += values[0];
sum += values[1];
firstTotal += values[0];
firstTotal += values[1];
for (int i = 3; i <= n; i++) {
sum += values[i - 1];
canFisrtPlayerTake[i] = !canFisrtPlayerTake[i - 1] || !canFisrtPlayerTake[i - 2];
if (canFisrtPlayerTake[i])
firstTotal += values[i - 1];
}
return firstTotal > (sum / 2);
}
}