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

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.
LeetCode 877. Stone Game解题报告(python)_第1张图片

解析

首先分析题目,发现题目有限定。一共有偶数个数,然后这偶数个数的和为奇数。说明不会存在平局现象。然后每人只能选第一个数或者最后一个数,这就意味着先选的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

你可能感兴趣的:(LeetCode)