Coins in a Line I

Description

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?

If the first player wins, return true, otherwise return false.

Example

Example 1:

Input: [1, 2, 2]
Output: true
Explanation: The first player takes 2 coins.

Example 2:

Input: [1, 2, 4]
Output: false
Explanation: Whether the first player takes 1 coin or 2,the second player will gain more value.
思路:博弈型动态规划。
public class Solution {
    /**
     * @param values: a vector of integers
     * @return: a boolean which equals to true if the first player will win
     */
     public boolean firstWillWin(int[] A) {
        int n = A.length;
        int[] f = new int[n + 1];
        f[n] = 0;
        int i;
        for (i = n - 1; i >= 0; --i){
            f[i] = A[i] - f[i + 1];
            if (i < n - 1) {
                f[i] = Math.max(f[i], A[i] + A[i + 1] - f[i + 2]);
            }
        }
        
        return f[0] >= 0;
    }
}

  

 

猜你喜欢

转载自www.cnblogs.com/FLAGyuri/p/12078231.html
今日推荐