[LintCode] Coins in a Line III

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?

 

备忘录,dp[left][right]表示从left到right所能取到的最大值,因为双方都取最优策略,所以取完一个后,对手有两种选择,我们要加让对手得到更多value的那种方案,也就是自己得到更少value的方案。

 1 class Solution {
 2 public:
 3     /**
 4      * @param values: a vector of integers
 5      * @return: a boolean which equals to true if the first player will win
 6      */
 7     bool firstWillWin(vector<int> &values) {
 8         // write your code here
 9         int n = values.size();
10         vector<vector<int>> dp(n + 1, vector<int>(n + 1, -1));
11         int sum = 0;
12         for (auto v : values) sum += v;
13         return sum < 2 * dfs(dp, values, 0, n - 1);
14     }
15     int dfs(vector<vector<int>> &dp, vector<int> &values, int left, int right) {
16         if (dp[left][right] != -1) return dp[left][right];
17         if (left == right) {
18             dp[left][right] = values[left];
19         } else if (left > right) {
20             dp[left][right] = 0;
21         } else {
22             int take_left = min(dfs(dp, values, left + 2, right), dfs(dp, values, left + 1, right - 1)) + values[left];
23             int take_right = min(dfs(dp, values, left, right - 2), dfs(dp, values, left + 1, right - 1)) + values[right];
24             dp[left][right] = max(take_left, take_right);
25         }
26         return dp[left][right];
27     }
28 };

 

转载于:https://www.cnblogs.com/easonliu/p/4741058.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值