#395 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.

题目思路:

这题的思路和#394类似:自己有两种选择:拿1或者拿2.但是对手的选择(1或者2)都是必须让自己拿的最少的。自己拿1的时候:对手的选择是dp[i - 3]和dp[i-2]里取最小;自己拿2的时候,对手在dp[i - 4]和 dp[i - 3]取最小。但是自己可以在拿1和拿2中选个最大值。

这题比较坑爹的是要注意初始化啊初始化。必须要从array的尾巴开始初始化和计算,因为从头看是有uncertainty的,我们是不知道到底应该怎么取的。

Mycode(AC = 11ms):

class Solution {
public:
    /**
     * @param values: a vector of integers
     * @return: a boolean which equals to true if the first player will win
     */
    bool firstWillWin(vector<int> &values) {
        // write your code here
        if (values.size() == 0) {
            return false;
        }
        else if (values.size() <= 2) {
            return true;
        }
        else if (values.size() == 3) {
            return values[0] + values[1] > values[2];
        }
        else {
            int n = values.size();
            vector<int> dp(n + 1, 0);
            
            // must initial from tail, because
            // how to pick from head is uncertain
            dp[1] = values[n - 1];
            dp[2] = values[n - 1] + values[n - 2];
            dp[3] = values[n - 3] + values[n - 2];
            
            int total = values[0] + values[1] + values[2];
            
            for (int i = 4; i <= values.size(); i++) {
                total += values[i - 1];
                dp[i] = max(min(dp[i - 4], dp[i - 3]) + values[n - i + 1] + values[n - i], // if player1 pick 2 coins
                            min(dp[i - 3], dp[i - 2]) + values[n - i]); // if player 1 pick 1 coin
            }
            
            return dp[n] > total - dp[n];
        }
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值