Nice one to learn: DP + Game Theory
https://lefttree.gitbooks.io/leetcode/content/dynamicProgramming2/coinsInLine2.html
In game theory, we assume the other player always take optimal step too. Combining with DP, we put this assumption together with each DP selection.
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) {
int n = values.size();
if(n<) return true; // Backward DP: since dp[a] -> dp[b] where a > b
vector<long long> dp(n, );
// init
dp[n-] = values[n-]; // pick 1
dp[n-] = values[n-] + values[n-]; // pick 2 for(int i = n - ; i >= ; i --)
{
int dp2 = ,dp3 = , dp4 = ;
if(i < n - ) dp4 = dp[i + ];
if(i < n - ) dp3 = dp[i + ];
if(i < n - ) dp2 = dp[i + ]; // we pick min because the other player is smart too
int v1 = values[i] + min(dp2, dp3); // pick 1
int v2 = values[i] + values[i + ] + min(dp3, dp4); // pick 2
dp[i] = max(v1, v2);
} long long suma = accumulate(values.begin(), values.end(), );
return dp[] > (suma - dp[]);
}
};