LintCode "Coins in a Line III" !!

https://codesolutiony.wordpress.com/2015/05/24/lintcode-coins-in-a-line-iii/

A very juicy one! Deserve more consideration.

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 < 2) return true;
    
    // Step 1: Find Variables
    //       since it is 2-end a single dim i is not enough, so - i, j (left, right)
    //       and dp[i][j] is the max value Play1 can get in [i, j]
    vector<vector<int>> dp(n, vector<int>(n));
    
    // Step 2: Choice strategy
    //       Apparently in every step, we have 2 choices: pick left or right
    //       so dp[i][j] should depends on dp[i-1][j] and dp[i][j-1]
    //
    // Step 2.5 Game Thoery
    //       In each choice at step2, we always Play2 always made the optimal
    //       choice in last step
    //
    // Equation
    //    dp[i][j] = max(
    //            values[i] + sum[i+1][j] - dp[i+1][j],
    //            values[j] + sum[i][j-1] - dp[i][j-1]
    //              );
    
    vector<int> presum(n);
    partial_sum(values.begin(), values.end(), presum.begin());
    
    for(int j = 0; j < n; j ++)
    for(int i = j; i >= 0; i --)
    {
        if (i == j)
        {
          dp[i][j] = values[i];
        }
        else
        {
          int sumij = presum[j] - (i > 0 ? presum[i - 1] : 0);
          dp[i][j] = sumij - min(dp[i+1][j], dp[i][j-1]);
        }
    }
    
    return dp[0][n-1] > (presum.back() - dp[0][n-1]);
    }
};
原文地址:https://www.cnblogs.com/tonix/p/4966431.html