Coins in a Line III

There are n coins in a line, and value of i-th coin is values[i].

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

Example 1:

Input: [3, 2, 2]
Output: true
Explanation: The first player takes 3 at first. Then they both take 2.

Example 2:

Input: [1, 20, 4]
Output: false
Explanation: The second player will take 20 whether the first player take 1 or 4.

Challenge

O(1) memory and O(n) time when n is even.

思路:跟Coins in a Line II,一样,转移方程考虑减去对手能够取得的最大值,f[i][j] 表示面对i~j的coins,我能得到的最大的与对手的数字差;

f[i][j] = Math.max(A[i] - f[i+1][j], A[j] - f[i][j-1]); 初始值f[i][i] = A[i]; 区间型动态规划,从len开始循环,枚举start index i,然后枚举所有的k,最后判断f[0][n-1] >=0; 用len做为外循环,模板走起;初始值f[i][i] = A[i]; 区间+博弈;

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) {
        if(A == null || A.length == 0) {
            return false;
        }
        int n = A.length;
        int[][] f = new int[n][n];
        // f[i][j]表示,面对i ~ j的coins,能够取得的最大值;
        for(int i = 0; i < n; i++) {
            f[i][i] = A[i];
        }
        
        // f[i][j] = Math.max(A[i-1] - f[i+1][j], A[j-1] - f[i][j+1]);
        for(int len = 2; len <= n; len++) {
            for(int i = 0; i + len - 1 < n; i++) {
                int j = i + len - 1;
                f[i][j] = Math.max(A[i] - f[i + 1][j], A[j] - f[i][j - 1]);
            }
        }
        return f[0][n - 1] >= 0;
    }
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值