美文网首页
Coins In A Line II

Coins In A Line II

作者: Star_C | 来源:发表于2018-04-05 23:00 被阅读0次

    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);
        }
    }
    

    相关文章

      网友评论

          本文标题:Coins In A Line II

          本文链接:https://www.haomeiwen.com/subject/jrtjhftx.html