令数组dp【i】【j】表示从i到j第一个player可以选取到的最大值,dp【i】【j】=选取左边后可选取的最大值或选取右边后可选取的最大值,设left为选取左边后可取的最大值,left=nums[i]+sum[i+1][j]-dp[i+1][j];(在player1选取后,player2也会在i+1--j间选取最大值,那么剩下的便是player1选取的),同理right=nums[j]+sum[i][j-1]-dp[i][-1j];
代码如下:
class Solution {
public:
bool PredictTheWinner(vector<int>& nums) {
int dp[nums.size()][nums.size()];
for(int i=0;i<nums.size();i++) dp[i][i]=nums[i];
for(int i=0;i<nums.size()-1;i++) dp[i][i+1]=max(nums[i],nums[i+1]);
vector<int> Sum(nums.size()+1);
Sum[0] = 0;
for (int i=0; i<nums.size(); i++) {
Sum[i+1] = Sum[i] + nums[i];
}
for (int len=1; len<=nums.size(); len++) {
for (int lhs=0; lhs+len-1<nums.size(); lhs++) {
int rhs = lhs + len - 1;
if (lhs == rhs) {
dp[lhs][rhs] = nums[lhs];
} else if (lhs == rhs-1) {
dp[lhs][rhs] = max(nums[lhs], nums[rhs]);
} else {
int pickLeft = nums[lhs] + Sum[rhs+1] - Sum[lhs+1] - dp[lhs+1][rhs];
int pickRight = nums[rhs] + Sum[rhs] - Sum[lhs] - dp[lhs][rhs-1];
dp[lhs][rhs] = max(pickLeft, pickRight);
}
}
}
if(dp[0][nums.size()-1]>=Sum[nums.size()-1]/2+1) return true;
else return false;
}
};