AC cpp DP O (N ^ 2)


  • 0
    M

    dp[i][j] = max(sum[i][j] - dp[i+1][j], sum[i][j] - dp[i][j-1]);
    dp[i][i] = coin[i]
    sum[i][j] is the total value from num i to num j
    dp[i][j]: the max value current player can get.

    bool PredictTheWinner(vector<int>& nums) {
      int n = nums.size();
      if (n < 1) {
        return false;
      }
      
      vector<int> sum(n + 1, 0);
      for (int i = 1; i <= n; i++) {
        sum[i] = sum[i - 1] + nums[i - 1];
      }
      
      vector<vector<int>> tbl(n, vector<int>(n, 0));
      
      for (int len = 1; len <= n; len++) {
        for (int i = 0; i + len - 1 < n; i++) {
          int j = i + len - 1;
          if (len == 1) {
            tbl[i][i] = nums[i];
            continue;
          }
          int tmp = sum[j + 1] - sum[i];
          tbl[i][j] = max(tmp - tbl[i + 1][j], tmp - tbl[i][j - 1]);
        }
      }
      
      return tbl[0][n - 1] * 2 >= sum[n];
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.