Leetcode486. Predict the Winner

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
                

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值