LintCode 396: Coins in a Line III (博弈类DP经典题)

  1. Coins in a Line III

There are n coins in a line. Two players take turns to take a coin from one of the ends of the line until there are no more coins left. The player with the larger amount of money wins.

Could you please decide the first player will win or lose?

Example
Given array A = [3,2,2], return true.

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

Given array A = [1,20,4], return false.

Challenge
Follow Up Question:

If n is even. Is there any hacky algorithm that can decide whether first player will win or lose in O(1) memory and O(n) time?

解法1:DP。
思路:还是把两个选手当成一个人,每次面对a[i…j]选最优解。
这里dp[i][j]是当前选手对a[i…j]所选的coins与对手将要选的coins的最大差值。
转移方程:
f[i][j] = max{a[i] - f[i+1][j], a[j] - f[i][j-1]}
注意:

  1. 初始条件:dp[i][i] = values[i]。因为只有1个coin,肯定是全选。
  2. dp计算顺序为:
    dp[0][0], dp[1][1], dp[2][2], …, dp[n-1][n-1] //len = 0, 1 coin
    dp[0][1], …, dp[n-2][n-1] //len = 1, 2 coins

    dp[0][n-1] //len = n - 1, n coins
    代码如下:
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) {
        int n = values.size();
        if (n <= 1) return true;
        vector<vector<int>> dp(n, vector<int>(n, 0));
        
        for (int i = 0; i < n; ++i) {
            dp[i][i] = values[i];
        }
        
        for (int len = 1; len < n; ++len) {
            for (int i = 0; i + len < n; ++i) {
                int j = i + len;
                dp[i][j] =  max(values[i] - dp[i + 1][j], values[j] - dp[i][j - 1]);
            }
        }
        return dp[0][n - 1] >= 0;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值