zoukankan      html  css  js  c++  java
  • 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]);
        }
    };
  • 相关阅读:
    centos7 安装 nginx
    centos7 安装 mysql
    centos7 安装 python3.7
    nginx添加到系统命令中
    Java多线程6-线程让步
    Java多线程5-线程等待与唤醒
    Java多线程4-synchronized关键字
    Java多线程3-Thread中start和run方法的区别
    Java多线程-2-常用的实现多线程的两种方式
    java多线程1-基础概念
  • 原文地址:https://www.cnblogs.com/tonix/p/4966431.html
Copyright © 2011-2022 走看看