[leetcode] 1140. Stone Game II

Description

Alice and Bob continue their games with piles of stones. There are a 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.

Alice and Bob take turns, with Alice starting first. Initially, M = 1.

On each player’s turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M. Then, we set M = max(M, X).

The game continues until all the stones have been taken.

Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get.

Example 1:

Input: piles = [2,7,9,4,4]
Output: 10
Explanation:  If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger. 

Example 2:

Input: piles = [1,2,3,4,5,100]
Output: 104

Constraints:

  1. 1 <= piles.length <= 100
  2. 1 <= piles[i] <= 104

分析

题目的意思是:两个人拿石子的游戏,Alice首先开始拿,M初始化为1,在每个玩家的回合中,该玩家可以拿走剩下的前X堆的所有石子,其中 1 <= X <= 2M。然后,令 M = max(M, X)。一直持续到所有的石子都被拿走。这道题用dp,我分享一下别人的思路:

  1. dp[i][j]表示当前位于第i个位置且M为j时,先手能取到的最大的石子数量。
  2. 需要从后往前遍历,因为最后的状态都可以直接得到。维护后缀求和数组sums
  3. 有效位置的下标从0到n-1,M的下标从1到n,初始化:对于所有的1<=j<=n, f(n,j)=0,这是边界
  4. 递推时需要枚举这一次先手取多少个石子k,满足1<=k<=2*j,且i+k<=n
dp[i][j]=max(dp[i][j],sum[i]-dp[i+k][max(j,k)])
  1. 最后答案是dp[0][1],表示当前在第0个位置,且M为1时先手能取到的最大值。

代码

class Solution:
    def stoneGameII(self, piles: List[int]) -> int:
        n=len(piles)
        sums=[0]*(n+1)
        dp=[[0]*(n+1) for i in range(n+1)]
        for i in range(n-1,-1,-1):
            sums[i]=sums[i+1]+piles[i]
        
        for i in range(n-1,-1,-1):
            for j in range(1,n+1):
                for k in range(1,2*j+1):
                    if(i+k<=n):
                        dp[i][j]=max(dp[i][j],sums[i]-dp[i+k][max(j,k)])
        return dp[0][1]

参考文献

[LeetCode] LeetCode 1140. Stone Game II
[Java] 动态规划 清晰易懂17行 演示

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值