**[Lintcode]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.

此题同样适用DP。res[i]代表从i到最后能取到的最大值。公式为:

res[i] = max(values[i] + min(res[i + 2], res[i + 3]), values[i] + min(res[i + 3], res[i + 4]))

第一种情况是后手取i+1,第二种情况是后手取i+1和i+2. 后手每次也是尽量取尽可能大的value,所以要在剩下的values中取最小的。如果题目改成问先手是否有可能赢,那么此处可以使用max。即为后手失误取最小值的情况。


public class Solution {
    /**
     * @param values: an array of integers
     * @return: a boolean which equals to true if the first player will win
     */
    public boolean firstWillWin(int[] values) {
        if(values.length <= 2) return true;
        if(values.length < 4) {
            return values[0] + values[1] > values[2];
        }
        int total = values[values.length - 1] + values[values.length - 2];
        int[] res = new int[values.length];
        res[values.length - 1] = values[values.length - 1];
        res[values.length - 2] = values[values.length - 2] + values[values.length - 1];
            
        for(int i = values.length - 3; i >= 0; i--) {
            total += values[i];
            int pos3 = i + 3 >= values.length ? 0 : res[i + 3];
            int pos4 = i + 4 >= values.length ? 0 : res[i + 4];
            int first = values[i] + Math.min(res[i + 2], pos3);
            int second = values[i] + values[i + 1] + Math.min(pos3, pos4);
            res[i] = Math.max(first, second);
        }
        int second = total - res[0];
        return res[0] > second;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值