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.
class Solution {
public:
bool PredictTheWinner(vector<int>& nums) {
int size = nums.size();
int f[size][size];
for(int i = 0; i < size; i ++)
{
f[i][i] = nums[i];
}
for(int i = 1; i < size; i ++)
{
for(int j = 0; i+j < size; j ++)
{
f[j][i+j] = max(nums[i+j] - f[j][i+j-1],nums[j] - f[j+1][i+j]);
}
}
return f[0][size-1] >= 0;
}
};
本文介绍了一种预测两位玩家在游戏中谁将获胜的算法。通过分析一个整数数组,该算法可以判断先手玩家是否能赢得比赛。每轮游戏,玩家从数组两端选择一个数,直到所有数被选完。
2029

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



