Leetcode 486 Predict the Winner
题目原文
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
Example 1:
Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2.
If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2).
So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.
Hence, player 1 will never be the winner and you need to return False.
Example 2:
Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.
Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Note:
- 1 <= length of the array <= 20.
- Any scores in the given array are non-negative integers and will not exceed 10,000,000.
- If the scores of both players are equal, then player 1 is still the winner.
题意分析
给一组分数,1和2两个人轮流取数组两端的元素,判断选取完毕后玩家1是否能获胜,获胜条件为分数大于等于对手。
解法分析
本题采用动态规划方法,dp[i][j]表示从数组nums[i]~nums[j]开始先手拿数的玩家能比另一个玩家多的分数dp[i][j]=max(nums[i]-dp[i+1][j],nums[j]-dp[i][j-1])。C++代码如下:
class Solution {
public:
bool PredictTheWinner(vector<int>& nums) {
int n=nums.size();
int **dp=new int *[n];
int i;
for(i=0;i<n;i++){
dp[i]=new int[n];
dp[i][i]=nums[i];
}
int len,j;
for(len=1;len<n;len++){
for(i=0;i<=n-len-1;i++){
j=i+len;
dp[i][j]=max(nums[i]-dp[i+1][j],nums[j]-dp[i][j-1]);
}
}
return dp[0][n-1]>=0;
}
};
本题还可以将dp[i][j]作为对于子数组[nums[i],nums[j]],先手选手能够获得的最大分数,同时需要注意,如果dp[i][j]是p1的分数,则dp[i+1][j]和dp[i][j-1]就是p2的分数,因此如果p1选择左端的元素,则dp[i][j]=nums[i]+(sum[i+1][j]-dp[i+1][j]),这里小括号里为p2最优后剩给p1的分数。C++代码如下:
bool PredictTheWinner(vector<int>& nums) {
vector<vector<int>> score(nums.size(), vector<int>(nums.size()));
vector<int> prefixSum(nums.size()+1);
prefixSum[0] = 0;
for (int i=0; i<nums.size(); i++) {
prefixSum[i+1] = prefixSum[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) {
score[lhs][rhs] = nums[lhs];
} else if (lhs == rhs-1) {
score[lhs][rhs] = max(nums[lhs], nums[rhs]);
} else {
int pickLeft = nums[lhs] + prefixSum[rhs+1] - prefixSum[lhs+1] - score[lhs+1][rhs];
int pickRight = nums[rhs] + prefixSum[rhs] - prefixSum[lhs] - score[lhs][rhs-1];
score[lhs][rhs] = max(pickLeft, pickRight);
}
}
}
return score[0][nums.size()-1] >= prefixSum.back()/2 + prefixSum.back()%2;
}
只要p1的分数总和超过sum的一半即可。