zoukankan      html  css  js  c++  java
  • 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?

    Example

    Given values array A = [1,2,2], return true.

    Given A = [1,2,4], return false.

    解题思路:

    题目要求用到动态规划,采用逆向思维, 不论对于哪一位选手, 假设他正站在第i个硬币的位置上,那么他在这个位置开始,他能领先另一位选手的硬币数量为 Gap[i]

    那么Gap[i]= Coin[i]-Gap[i+1] //如果只拿一个

    或者Gap[i]=Coin[i]+Coin[i+1]-Gap[i+2] 如果只拿一个

    从最后一个硬币的位置开始推

    Gap[last]=Gap[last]; //最后只能拿一个;

    Gap[last-1]=coin[last-1]+coin[last]; //把最后两个都拿了

    从倒数第三个开始递减循环,直到第一个硬币的位置, 因为第一个硬币无论如何都是第一个选手拿,那只要Gap[0]>0 那么就能获胜

    代码:

     public boolean firstWillWin(int[] values) {
            // write your code here
            int length = values.length;
            if(length<=2) return true;
            int[] largestPossibleSum = new int[length];
            // for the last turn
            largestPossibleSum[length-1]=values[length-1];//if there is one last coin avaliable for this player
            largestPossibleSum[length-2]=values[length-2]+values[length-1];// if there are only two coins available for this player
            
            //for each the coins from length-3 to 0, find each possible max sum he could get at each index
            for(int i= length-3;i>=0;i--){
                largestPossibleSum[i]=Math.max(values[i]-largestPossibleSum[i+1],
                                      values[i]+values[i+1]-largestPossibleSum[i+2]);
            }
            
            return(largestPossibleSum[0]>0);
        }
  • 相关阅读:
    C# 解析JSON字符串
    C# 调用SAP RFC
    【Vue】vue动态添加表单项
    2020年余额不足,送你3本Python好书充值
    中国编程第一人,一人抵一城!
    2020年测试工作总结!
    这段代码,我在本地运行没问题啊
    我28岁,财务自由168天,却写下一封遗书...
    困惑大家这么多年的区块链技术,终于被沈阳一小区大门给讲明白了
    年轻人越来越有出息的迹象
  • 原文地址:https://www.cnblogs.com/midan/p/4709689.html
Copyright © 2011-2022 走看看