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.
Cocould you please decide the first player will win or lose?
Example
Given array A =[3,2,2], Returntrue.
Given array A =[1,2,4], Returntrue.
Given array A =[1,20,4], Returnfalse.
Challenges
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?
Analysis: It seems to be a dynamic planning, but the status is indeed a bit difficult to express. You can use DP [I] [J] to represent the segment from I to J, the maximum value of the first hand and the maximum value of the last hand, saved with a pair <int, int>, if DP [I + 1] [J] and DP [I] [J-1] are known, then we can enumerate the two ends to determine DP [I] [J].
Code:
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; }};
Lintcode-coins in a line III