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.

题目链接

解体思路

本题也是 Game Theory, 可以使用 DP 解决。 状态 dp[i] 为从左边第 i 个数开始拿,先手最多可以拿到的钱数。

参考代码

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
        int n = values.size();
        vector<int> dp(n + 1, INT_MIN);
        dp[n] = 0;
        dp[n - 1] = values[n - 1];
        int sum = values[n - 1];
        for (int i = n - 2; i >= 0; -- i) {
            sum += values[i];
            dp[i] = max(dp[i], sum - dp[i + 1]);
            dp[i] = max(dp[i], sum - dp[i + 2]);
        }
        return dp[0] + dp[0] > sum;
    }
};

results matching ""

    No results matching ""