LeetCode 877. Stone Game解题报告(python)

本文深入探讨了LeetCode上877.StoneGame题目的策略分析与解题思路,通过动态规划方法详细解释了如何在一系列石堆中,通过选择最优策略来确保游戏胜利。文章揭示了先手玩家Alex如何通过选择最大数列获得优势,同时提供了Python代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

877. Stone Game

  1. Stone Game python solution

题目描述

Alex and Lee play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].
The objective of the game is to end with the most stones. The total number of stones is odd, so there are no ties.
Alex and Lee take turns, with Alex starting first. Each turn, a player takes the entire pile of stones from either the beginning or the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins.
Assuming Alex and Lee play optimally, return True if and only if Alex wins the game.
在这里插入图片描述

解析

首先分析题目,发现题目有限定。一共有偶数个数,然后这偶数个数的和为奇数。说明不会存在平局现象。然后每人只能选第一个数或者最后一个数,这就意味着先选的alex可以决定他选奇数列还是偶数列,因为奇数列和偶数列的和必然不同,所以先选的alex只需选择大的数列即可,则alex必胜。
另一种通用的思想是动态规划,
dp[i][j] 代表在piles[i] ~ piles[j]你选取的石头可比对手多几个。你可以先选择piles[i]或者piles[j],
如果你选择了piles[i], 得到的结果会是piles[i] - dp[i + 1][j]
如果选择piles[j], 得到结果会是piles[j] - dp[i][j - 1]
所以我们得到dp[i][j] = max(piles[i] - dp[i + 1][j], piles[j] - dp[i][j - 1])

class Solution:
    def stoneGame(self, piles: List[int]) -> bool:
        n = len(piles)
        dp = [[0] * n for i in range(n)]
        for i in range(n): 
            dp[i][i] = piles[i]
        for d in range(1, n):
            for i in range(n - d):
                dp[i][i + d] = max(piles[i] - dp[i + 1][i + d], piles[i + d] - dp[i][i + d - 1])
        return dp[0][-1] > 0
            

Reference

https://leetcode.com/problems/stone-game/discuss/154610/DP-or-Just-return-true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值