当前位置:网站首页>【LeetCode】1140-石子游戏II
【LeetCode】1140-石子游戏II
2022-07-02 12:09:00 【酥酥~】
爱丽丝和鲍勃继续他们的石子游戏。许多堆石子 排成一行,每堆都有正整数颗石子 piles[i]。游戏以谁手中的石子最多来决出胜负。
爱丽丝和鲍勃轮流进行,爱丽丝先开始。最初,M = 1。
在每个玩家的回合中,该玩家可以拿走剩下的 前 X 堆的所有石子,其中 1 <= X <= 2M。然后,令 M = max(M, X)。
游戏一直持续到所有石子都被拿走。
假设爱丽丝和鲍勃都发挥出最佳水平,返回爱丽丝可以得到的最大数量的石头。
示例 1:
输入: piles = [2,7,9,4,4]
输出: 10
解释: 如果一开始Alice取了一堆,Bob取了两堆,然后Alice再取两堆。爱丽丝可以得到2 + 4 + 4 = 10堆。如果Alice一开始拿走了两堆,那么Bob可以拿走剩下的三堆。在这种情况下,Alice得到2 + 7 = 9堆。返回10,因为它更大。
示例 2:
输入: piles = [1,2,3,4,5,100]
输出: 104
提示:
- 1 <= piles.length <= 100
- 1 <= piles[i] <= 104
思路
dp[M][i]表示剩余石子堆为piles[i : len]时,M = M的情况下,先取的人能获得的最多石子数
- i + 2M >= length, dp[M][i] = sum(piles[i : length]),剩下的堆数能够直接全部取走
- i + 2M < length, dp[M][i] = max(dp[M][i],sum(piles[i : length]) - dp[max(M, X)][i + X]), 其中 1 <= X <= 2M,剩下的堆数不能全部取走,那么最优情况就是让下一个人取的更少。对于此时所有的x取值,下一个人从X开始取起,M变为max(M, X),所以下一个人能取dp[max(M, X)][i + X],此事最多能取sum[i : len - 1] - dp[max(M, X)][i + X]
#动态规划
class Solution(object):
def stoneGameII(self, piles):
length = len(piles)
mysum = 0
dp = [[0 for i in range(length)] for j in range(length+1)]
for i in range(length-1,-1,-1):
mysum += piles[i]
for M in range(1,length+1):
if i+2*M>=length:
dp[M][i]=mysum
else:
for X in range(1,2*M+1):
dp[M][i] = max(dp[M][i],mysum-dp[max(M,X)][i+X])
return dp[0][1]
边栏推荐
- 百变大7座,五菱佳辰产品力出众,人性化大空间,关键价格真香
- 13_ Redis_ affair
- LeetCode刷题——奇偶链表#328#Medium
- 原则、语言、编译、解释
- Apprendre le Code de la méthode de conversion du calendrier lunaire grégorien en utilisant PHP
- 17_Redis_Redis发布订阅
- 2022 年辽宁省大学生数学建模A、B、C题(相关论文及模型程序代码网盘下载)
- 4. Jctree related knowledge learning
- 终于搞懂了JS中的事件循环,同步/异步,微任务/宏任务,运行机制(附笔试题)
- Solution of Queen n problem
猜你喜欢
随机推荐
5. Practice: jctree implements the annotation processor at compile time
19_ Redis_ Manually configure the host after downtime
夏季高考文化成绩一分一段表
JVM architecture, classloader, parental delegation mechanism
Apprendre le Code de la méthode de conversion du calendrier lunaire grégorien en utilisant PHP
工程师评测 | RK3568开发板上手测试
Summary of the first three passes of sqli Labs
Mavn builds nexus private server
PHP method to get the index value of the array item with the largest key value in the array
20_Redis_哨兵模式
使用 TiUP 部署 TiDB 集群
Data analysis thinking analysis methods and business knowledge - business indicators
Kibana basic operation
高考分数线爬取
06_栈和队列转换
07_ Hash
士官类学校名录
党史纪实主题公益数字文创产品正式上线
Libcurl Lesson 13 static library introduces OpenSSL compilation dependency
Solve the problem of frequent interruption of mobaxterm remote connection