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.
class Solution {
public:
bool PredictTheWinner(vector<int>& nums)
{
int all = 0;
for (auto it : nums) all += it;
return 2 * MaxCanFetch(nums, 0, nums.size() - 1, all) >= all;
}
int MaxCanFetch(vector<int>& nums, int start, int end, int all) //all是[start, end]的和,避免重复计算
{
if (start == end)
return nums[start];
else if (start + 1 == end)
return max(nums[start], nums[end]);
else
{
//A取开头,B取剩下的最多
int first = all - MaxCanFetch(nums, start + 1, end, all - nums[start]);
//A取末尾,B取剩下的最多
int second = all - MaxCanFetch(nums, start, end - 1, all - nums[end]);
return max(first, second);
}
}
};
本文介绍了一个基于数组中非负整数得分的两人博弈游戏。玩家轮流从数组两端选择分数,目标是获得比对手更高的总分。文章通过示例说明了如何判断先手玩家是否能赢得比赛,并提供了一种算法实现。
650

被折叠的 条评论
为什么被折叠?



