Coins in a line III
There is n coins in a line. A coin from one of the ends of the line until there is no more coins left. The player with the larger amount for money wins.
Could decide the first player would 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 would win or lose in O (1) memory and O (n) time ?
Memo, Dp[left][right] represents the maximum value that can be obtained from left to right, because both sides take the optimal strategy, so after taking one, the opponent has two options, we want to add to the opponent to get more value of the kind of scheme, that is, we get less value of the scheme.
1 classSolution {2 Public:3 /**4 * @param values:a vector of integers5 * @return: A Boolean which equals to True if the first player would win6 */7 BOOLFirstwillwin (vector<int> &values) {8 //Write your code here9 intn =values.size ();Tenvector<vector<int>> DP (n +1, vector<int> (n +1, -1)); One intsum =0; A for(auto v:values) sum + =v; - returnSum <2* DFS (DP, values,0N1); - } the intDFS (vector<vector<int>> &DP, vector<int> &values,intLeftintRight ) { - if(Dp[left][right]! =-1)returnDp[left][right]; - if(left = =Right ) { -Dp[left][right] =Values[left]; +}Else if(Left >Right ) { -Dp[left][right] =0; +}Else { A inttake_left = MIN (Dfs (DP, values, left +2, right), DFS (DP, values, left +1, right-1)) +Values[left]; at inttake_right = MIN (Dfs (DP, values, left, right-2), DFS (DP, values, left +1, right-1)) +Values[right]; -Dp[left][right] =Max (Take_left, take_right); - } - returnDp[left][right]; - } -};
[Lintcode] Coins in a line III