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?
Given array A = [3,2,2]
,
return true
.
Given array A = [1,2,4]
,
return true
.
Given array A = [1,20,4]
,
return false
.
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[i][j]表示从i到j这一段,先手的最大值和后手的最大值,用一个pair<int,int>保存,如果已知dp[i+1][j]和dp[i][j-1],那么就可以枚举两端确定dp[i][j]
代码:
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<vector<pair<int,int> > > dp(n,vector<pair<int,int> >(n,make_pair(0,0))); for(int len=1;len<=n;len++) { for(int i=0;i+len<=n;i++) { int j = i+len-1; if(i==j) dp[i][j] = make_pair(values[i],0); else { pair<int,int> p1 = dp[i+1][j]; pair<int,int> p2 = dp[i][j-1]; if(p1.second+values[i]>p2.second+values[j]) { dp[i][j] = make_pair(p1.second+values[i],p1.first); } else { dp[i][j] = make_pair(p2.second+values[j],p2.first); } } } } if(dp[0][n-1].first>dp[0][n-1].second) return true; else return false; } };
原文地址:http://blog.csdn.net/wangyuquanliuli/article/details/45922775