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

 

转载于:https://www.cnblogs.com/midan/p/4709689.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值