[Lintcode] Coins in a line III

Source: Internet
Author: User

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>> &AMP;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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.