You are given an integer array nums
. Two players are playing a game with this array: player 1 and player 2.
Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0
. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0]
or nums[nums.length - 1]
) which reduces the size of the array by 1
. The player adds the chosen number to their score. The game ends when there are no more elements in the array.
Return true
if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true
. You may assume that both players are playing optimally.
动态规划 两个玩家游戏的题 可以把dp变成一个玩家比另一个玩家多的最大分数
此题即为玩家1和玩家2在i,j之间轮流选取,玩家1比玩家2多的最大分数,最后只要看最大分数是否大于等于0即可
轮流选取,玩家1选完之后,玩家2的状态变成之前玩家1的状态 dp[i+1][j]是玩家2比玩家1多的最大分数,取负号再加上nums[i]就是玩家1选择nums[i]时超过玩家2的得分
class Solution:
def predictTheWinner(self, nums: List[int]) -> bool:
size = len(nums)
dp = [[0 for _ in range(size)] for _ in range(size)]
# 玩家1和玩家2在i,j之间轮流选取,玩家1比玩家2多的最大分数
for l in range(1, size + 1):
for i in range(size + 1 - l):
j = i + l - 1
if l == 1:
dp[i][j] = nums[i]
else:
dp[i][j] = max(nums[i] - dp[i+1][j], nums[j] - dp[i][j - 1])
return dp[0][size-1] >= 0