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);
        }
  • 相关阅读:
    postman发送请求携带Cookie
    maven打包相关配置
    springboot使用redis的keyspace notifications 实现定时通知
    JSON使用
    jdk1.8的一些特性
    Mysql--基础(一)
    04 difflib和filecmp
    08 存储引擎
    03 dnspython模块的应用
    02 IPy模块的应用
  • 原文地址:https://www.cnblogs.com/midan/p/4709689.html
Copyright © 2011-2022 走看看